Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if an object is an instance of subclass or superclass

Tags:

ios

swift

I have 2 classes:

class Parent
{
  func a() {
     self.b()
  }
  func b() {
     // I want to check here
     if self is Parent  // warning "'is' test is always true"
     {
        log("instance of parent")
     }
  }
}
class Child:Parent
{
}

I want to check like this

//
var child = Child()
child.a()  // don't see log
var parent = Parent()
parent.a()  // see log

I know that I can create a method like description in superclass, and override it in subclass. I wonder if Swift can check it without implement description

Thanks for your help

like image 683
tuledev Avatar asked Dec 28 '15 03:12

tuledev


2 Answers

Its really simple, use is keyword.

if child is Child
like image 119
Uros19 Avatar answered Sep 30 '22 19:09

Uros19


This can be accomplished using the as type cast operator:

var child = Child()

if let child = child as? Child {
    //you know child is a Child
} else if let parent = child as? Parent {
    //you know child is a Parent
}

There is also the is keyword:

if child is Child {
    //is a child
}

Note that in your code you're seeing a warning using is - it will always be true, because comparing self to Parent from within class Parent will always be true. If you were comparing it against some other instance of a class instead of self, or if you were comparing against some other type besides Parent, this warning would disappear.

I would recommend reading more about this in the Swift Programming Language book, found on the iBooks Store - see the Type Casting chapter.

like image 41
Jordan H Avatar answered Sep 30 '22 19:09

Jordan H