Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

whats the equivalent of java's instanceof in Swift?

Tags:

ios

swift

Just like java's instanceOf keyword whats the equivalent in Swift?

java example:

A a = new A(); boolean isInstanceOfA = a instanceof A; 

Here isInstanceOfA is true

So i need something similar in Swift

like image 669
Bhargav Avatar asked Jun 01 '16 08:06

Bhargav


People also ask

Why does instanceof return false?

Using the instanceof Operator When an Object Is nullIf we use the instanceof operator on any object that's null, it returns false. We also don't need a null check when using an instanceof operator.


2 Answers

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, whereas isKindOfClass() works only with those classes that are subclasses of NSObject or otherwise implement NSObjectProtocol.

  • 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

like image 104
Bhargav Avatar answered Sep 19 '22 10:09

Bhargav


For swift3 and swift4 it's:

if someInstance is SomeClass {     ... } 

if your class is extending NSObject you can also use:

if someInstance.isKind(of: SomeClass.self) {     ... } 
like image 22
algrid Avatar answered Sep 22 '22 10:09

algrid