Search code examples
swifttypessubclass

Swift - check if two objects are of same type or superclass-type


I want to check if two objects belong to - or are of - the same superclass.

class myClass {}
class mySubclass: myClass {}

let myObject = myClass()
let myOtherObject = myClass()
let mySubclassedObject = mySubclass()

I know that I can check the type this way:

type(of: myObject) == myClass.self                // true
type(of: myObject) == type(of: myOtherObject)     // true

type(of: mySubclassedObject) == myClass.self      // false

The last statement returns false, as type(of: <T>) obviously returns the object's final class.

Another way for type checking is the is keyword:

mySubclassedObject is mySubclass     // true
mySubclassedObject is myClass        // true 

Here both statements evaluate to true, as the is keyword is obviously considering the superclass. But what I can't do that way is comparing two objects' types like this:

myOtherObject is myObject   // Use of undeclared type 'myObject'

I need to get results like this:

myObject is myOtherObject        // true 
mySubclassedObject is myObject   // true
myObject is mySubclassedObject   // false

I was hoping to find something like .isSubclassOf but this seems to be unavailable in Swift. So how could I get my desired result?


Solution

  • One way could be to try generics like this

    func isObject<P>(_ object: Any, ofType other: P) -> Bool {
        object is P
    }
    
    isObject(myObject, ofType: myOtherObject)           //true
    isObject(mySubclassedObject, ofType: myObject)      //true
    isObject(myObject, ofType: mySubclassedObject)      //false