How to store a class reference and compare it with an instance in swift?

349 views Asked by At

I want to store a reference on a type to compare it later with an object.

I tried to do:

let myClassRef = AClass.self // store a reference to the type of AClass
if myObject is myClassRef {
    // Do something
}

But it just does not work. How to use a AnyClass object ? Alternatively, how to get an AnyClass object from an instance (this produce the same result as what I am expecting)

3

There are 3 answers

3
itsji10dra On BEST ANSWER

Make your Aclass subclass of NSObject & use isMemberOfClass()

let myClassRef = AClass.self // store a reference to the type of AClass

if myObject.isKindOfClass(myClassRef) {
// Do something
}
2
ABakerSmith On

To avoid having to subclass NSObject you could use dynamicType:

let myClassRef = AClass.self

if myObject.dynamicType === myClassRef {
    // ...
}
0
newacct On

It doesn't need to subclass NSObject.

If myObject is type AnyObject, you can just do this:

import Foundation

let myClassRef = AClass.self
let myObject : AnyObject = BClass()
if myObject.isKindOfClass(myClassRef) {
    // Do something
}

If myObject is a specific class or interface type, you can just cast it to AnyObject first:

import Foundation

let myClassRef = AClass.self
let myObject = BClass()
if (myObject as AnyObject).isKindOfClass(myClassRef) {
    // Do something
}