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
Its really simple, use is
keyword.
if child is Child
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With