whats the equivalent of java's instanceof in Swift?
isKindOfClass()
method, from NSObjectProtocol is the equivalent of java's instanceof keyword, in java it's a keyword but in swift it's a protocol method, but they behave similarly and are used in similar contexts.
isKindOfClass:
returns YES if the receiver is an instance of the specified class or an instance of any class that inherits from the specified class.
Which is exactly what instanceof keyword does in Java related link
Example:
let a: A = A()let isInstanceOfA: Bool = a.isKindOfClass(A) // returns true.
Also you can use the is
keyword
let a: A = A()let isInstanceOfA: Bool = a is A
The difference:
is
works with any class in Swift, whereasisKindOfClass()
works only with those classes that are subclasses ofNSObject
or otherwise implementNSObjectProtocol
.is
takes a type that must be hard-coded at compile-time.isKindOfClass:
takes an expression whose value can be computed at runtime.
So no is
keyword doesn't work like instanceof