mra214 mra214 - 1 year ago 72
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 Source

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:

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download