Comparing types with Swift

To compare instances use

type(of: instanceA) == type(of: instanceB)


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.self
var b : AnyClass = a

if(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.self
let 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: Equatable
func ==(lhs: Test, rhs: Test) -> Bool {
    return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}

var a = Test()
var b : AnyObject = a

if((b as Test) == a) {
    println("yes")
} else {
    println("no")
}

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 structs. 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 :)

Tags:

Ios

Swift