whats the equivalent of java's instanceof in Swift? whats the equivalent of java's instanceof in Swift? ios ios

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, 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


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) {    ...}


let a = A()let isInstanceOfA = a is A


matomo