As far as I can look, it seems that the consensus is that the is
in Swift keyword is synonymous to isKindOfClass
method.
However, I'm having trouble getting the following to work:
//inside of a method in UITabViewController
//check if the currently selected tab is ActivityViewController
if selectedViewController is ActivityViewController {
print("isActivity")
} else {
print("isNotActivity")
}
//same check
if selectedViewController?.isKindOfClass(ActivityViewController) != nil {
print("isActivity")
} else {
print("isNotActivity)
}
When this block of code was called, I made sure I was in my ActivityViewController
tab. isKindOfClass
was correct, selectedViewController is ActivityViewController
was not. Any ideas as to why this is?
Keywords used in statements: break , case , catch , continue , default , defer , do , else , fallthrough , for , guard , if , in , repeat , return , throw , switch , where , and while .
Types that conform to the Equatable protocol can be compared for equality using the equal-to operator ( == ) or inequality using the not-equal-to operator ( != ). Most basic types in the Swift standard library conform to Equatable .
In Swift, there are two kinds of types: named types and compound types. A named type is a type that can be given a particular name when it's defined. Named types include classes, structures, enumerations, and protocols. For example, instances of a user-defined class named MyClass have the type MyClass .
If you remove open from the whole User class it can be used but not subclassed. The open keyword is an effective way of stopping other developers from accidentally overriding functionality that's critical to the way your app works.
is
and isKindOfClass
are not synonyms, see for example
Is there a difference between "is" and isKindOfClass()?.
In your case however, the problem is the optional chaining.
selectedViewController?.isKindOfClass(ActivityViewController)
returns an Optional<Bool>
which is nil
if the call could not be
made (because selectedViewController
is nil
), and a non-nil
value otherwise. So
selectedViewController?.isKindOfClass(ActivityViewController) != nil
is true if the call could be made, independent of whether the
return value is true
or false
.
With
if selectedViewController?.isKindOfClass(ActivityViewController) == true { ... }
you would get the expected result.
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