mra214 mra214 - 7 months ago 18
Swift Question

Is it possible to check types in Swift like in C#?

Is it possible to do like this in Swift?

if (obj1.GetType() == obj2.GetType()) { /* do something */}

Answer

You could use the Mirror struct as mentioned in this question How do you find out the type of an object (in Swift)?
Here a few examples:

let var1 = "Test"
let var2 = "Hello World"
let var3 = UIView()
let var4 = UIView(frame: CGRect.zero)

let mirror1 = Mirror(reflecting: var1)
let mirror2 = Mirror(reflecting: var2)
let mirror3 = Mirror(reflecting: var3)
let mirror4 = Mirror(reflecting: var4)

print(mirror1.subjectType == mirror2.subjectType) // true
print(mirror2.subjectType == mirror3.subjectType) // false
print(mirror3.subjectType == mirror4.subjectType) // true
Comments