Reputation: 315
So in Obj-C I used to do it like this:
SKSpriteNode *someNode = [SKSpriteNode spriteNodeWithImageNamed:@"foo"];
someNode.position = CGPointMake(100,100);
someNode.size = CGSizeMake(100,100);
[self addChild:someNode]
//I'd test it like this:
if (someNode) {
//Do something
}
//I could also do it like this:
if (someNode != nil) {
//Do something
}
However, when I want to achieve the same thing in swift, it gives me the error: Binary operator '!=' cannot be applied to operands of type 'SKSpriteNode' and 'nil'
I did it like this:
if someNode != nil {
//Do something
}
I also tried this:
if someNode {
//Do something
}
This gives me the error: Type 'SKSpriteNode' does not conform to protocol 'BooleanType'
Is there a way to test if a node already exists?
Upvotes: 4
Views: 1179
Reputation: 35392
Basically you have to consider that SKSpriteNode
node derive from SKNode
, so it inherits all its properties according to Apple doc SKNode Class Reference:
In Swift 2.x the best general way to do is:
if let someNodeExist = self.childNodeWithName("\\someNode") {
print("\(someNodeExist.debugDescription)")
}
In Swift 3.x:
if let someNodeExist = self.childNode(withName: "\\someNode") {
print("\(someNodeExist.debugDescription)")
}
or using guard:
guard let someNodeExist = self.childNode(withName: "\\someNode") else { return }
After that you can check which kind of class is someNodeExist or casting directly to SKSpriteNode, you decide.
Upvotes: 2