Comparing types with Swift Comparing types with Swift ios ios

Comparing types with Swift


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 thereforebe compared with ===.

It won't work with structs. Perhaps someone has a better answer that works forall 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 just want to compare the class types, then you can simply use NSStringFromClass to compare the class names as below:

class Test {}var a = Test.selfvar b : AnyClass = aif(NSStringFromClass(b) == NSStringFromClass(Test.self)) {    println("yes")} else {    println("no")}

If you want to find out or compare the type of an object, you can use "if ... is ... {}" syntax as code below:

class Test { }class Testb { }var a = Test.selflet b : AnyObject = Testb()if(b is Test) {    println("yes")} else {    println("no")}

If you want to do object to object equality check with == operator, you can make your Test class conforms to Equatable protocol. This can be extended to both Struct and Class types in Swift as explained in this NSHipster article: http://nshipster.com/swift-comparison-protocols/.

You code then can be written as below, please note: this is object equality checking, so you cannot define b as AnyClass, you need to instead define as AnyObject.

class Test: Equatable { }// MARK: Equatablefunc ==(lhs: Test, rhs: Test) -> Bool {    return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)}var a = Test()var b : AnyObject = aif((b as Test) == a) {    println("yes")} else {    println("no")}


matomo