Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"is" keyword in Swift

Tags:

ios

swift

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?

like image 744
Kelvin Lau Avatar asked Sep 28 '15 18:09

Kelvin Lau


People also ask

What is is keyword used for Swift?

Keywords used in statements: break , case , catch , continue , default , defer , do , else , fallthrough , for , guard , if , in , repeat , return , throw , switch , where , and while .

What does != Mean in Swift?

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 .

Is kind of Swift?

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 .

What is open keyword in Swift?

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.


1 Answers

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.

like image 98
Martin R Avatar answered Sep 30 '22 04:09

Martin R