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