I'm looking to do something like the following, but when I try to see if b == Test.self I get the error "Any class is not convertible to MirrorDisposition". How can I checked to see if a Type is equal to another type?
class Test { } var a = Test.self var b : AnyClass = a if(b == Test.self) { println("yes") } else { println("no") }
The == Operator In Swift, variables can be value types or reference types. The first “family” of variables holds values, whereas the second holds memory references. So if you're using objects instantiated by a class schema, the == operator compares references and not values.
The difference between == and === in Swift is: == checks if two values are equal. === checks if two objects refer to the same object.
The === or identity operator compares the identity of the objects. It checks whether the operands refer to the same object. As you can see, arr1 and arr2 do not refer to the same object, despite the objects being equal.
Use the "identical to" operator ===
:
if b === Test.self { print("yes") } else { print("no") }
This works because the type of a class is itself a class object and can therefore be compared with ===
.
It won't work with struct
s. Perhaps someone has a better answer that works for all Swift types.
if b.isKindOfClass(Test) { println("yes") } else { println("no") }
Edit: Swift 3
if b.isKind(of: Test.self) { print("yes") } else { print("no") }
try it :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With