2

I have seen various answers to similar questions here, but this is different (in particular, this very extensive answer here did not help.

Let me explain: If you are inside the scope of a parent class, how can you - in just one line of code - rule out that an object is an instance of precisely this class but NOT an instance of any of that classes' child's class?

Code example:

class Subchild: Child {
     //blabla
}

class Child: Parent {
     //blabla
}

class Parent {
    //....could be NSObject or generic Swift class
    func iAmNotARealParent() -> Bool {
        enter code here
    }    
}

... so that I can do:

let myObject:Subchild = ...
myObject.iAmNotARealParent()   //<--- returns true

let anotherObject:Child = ...
anotherObject.iAmNotARealParent() //<---- returns true

let thirdObject:Parent = ...
thirdObject.iAmNotARealParent() //<---- returns false

In my particular case I am dealing with trying to identify inside UIViews whether "self" is an actual UIView, or any of its many subclasses (UIButton, etc). I do not want to have to check it like this:

if self is UIBUtton {return false}
if self is UIScrollView {return false} 

etc., because then I have to exclude explicitly all child classes.

How do I do this? Is there a *exactClassOf / exactTypeOf * function in Swift I missed? Note I am looking for a solution for both Swift-derived and NSObject derived classes (i.e. for Any)

Community
  • 1
  • 1
Averett
  • 66
  • 8

1 Answers1

2

You can use something like:

if type(of: self) == Parent.self {
    // this only runs for exact type matches, not subclasses
}

That checks for equality of the types rather than polymorphic conformance of the instance (i.e. self is Parent)

Daniel Hall
  • 13,457
  • 4
  • 41
  • 37