Basic Card object:
import Foundation
import SpriteKit
class Card: SKSpriteNode {
var cardValue:Int = 0
init() {
cardValue = 10
}
...
}
Why am I not able to read this value when it's a child of an SKNode? When debugging with lldb
, it is showing me the value inside the whole object, but I can't access it:
(lldb) p handsOnScreen.children[0]
(BlackJack.Card) $R0 = 0x00007f84937a21a0 {
SpriteKit.SKSpriteNode = {
SKNode = {
UIResponder = {
NSObject = {
isa = Blackjack.Card
}
_hasAlternateNextResponder = false
_hasInputAssistantItem = false
}
_parent = 0x00007f8493708b60
_children = nil
_actions = nil
_keyedActions = nil
_keyedSubSprites = nil
_info = nil
_attributeValues = nil
_name = nil
_userData = nil
_constraints = nil
_version = 17096000
_userInteractionEnabled = false
_reachConstraints = nil
}
_light = nil
_shouldRepeatTexture = false
}
cardValue = 10
...
After seeing that output, I thought I could just try this:
(lldb) p handsOnScreen.children[0].cardValue
error: <EXPR>:1:35: error: value of type 'SKNode' has no member 'cardValue'
What am I doing wrong?
You must cast your SKNode
to Card
in order to access its properties.
if let card = handsOnScreen.children[0] as? Card {
print(card.cardValue)
}
I used an if let
statement instead of force unwrapping (as!
) to be safe in case the object at children[0]
would happen to not be a Card
.