In swift you can check if an object is of a specific type using something similar to the following
let object: AnyObject = someOtherObject
if object is SKNode {
//is SKNode
}
In this case SKShapeNode and SKSpriteNode would also satisfy this condition as they subclass SKNode.
What is the standard way to detect if an object is of a specific type and not a subclass of that type?
“Use the type check operator (is) to check whether an instance is of a certain subclass type. The type check operator returns true if the instance is of that subclass type and false if it is not.” Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.
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 .
You could fall back to Objective-C:
if (object as AnyObject).isMemberOfClass(SKNode) {
//is SKNode
}
The Apple-approved way to do this in Swift 2.2 is:
if object.dynamicType === SKNode.self {
// is node
}
and once this proposal is implemented (Swift 3.0), it will change to:
if object.Self === SKNode.self {
// is node
}
This is not how the is
operator works. If you do that, you'll get a compile error.
The is
operator is used to check whether an object of a particular type is of a given sub-type. Using SKNode
and SKShapeNode
as examples, you'd use is
to verify whether a object typed as SKNode
is an SKShapeNode
or an SKSpriteNode
.
Paste this into a playground to get an idea of how it works:
let shape: SKNode = SKShapeNode()
let sprite: SKNode = SKSpriteNode()
let anotherShape = SKShapeNode()
if shape is SKShapeNode {
println("is shape")
}
if sprite is SKSpriteNode {
println("is sprite")
}
if shape is SKNode {
//this raises a compile error, because the test is always true
}
if anotherShape is SKNode {
//this raises a compile error, because SKNode is not a subtype of SKShapeNode
}
In swift 3:
if type(of: object) == SKNode.self {
// is node
}
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