Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if an object is exactly a specific type and not a subclass of that type in swift

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?

like image 791
nacross Avatar asked Jul 01 '14 13:07

nacross


People also ask

How do you check if an object is of a certain class Swift?

“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.

What is type () in Swift?

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 .


4 Answers

You could fall back to Objective-C:

if (object as AnyObject).isMemberOfClass(SKNode) {
   //is SKNode
}
like image 108
Ashley Mills Avatar answered Oct 13 '22 21:10

Ashley Mills


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
}
like image 32
inket Avatar answered Oct 13 '22 23:10

inket


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
}
like image 45
Cezar Avatar answered Oct 13 '22 23:10

Cezar


In swift 3:

if type(of: object) == SKNode.self {
   // is node
}
like image 34
Amr Avatar answered Oct 13 '22 22:10

Amr