从子SKSpriteNode

时间:2015-11-29 04:51:50

标签: ios swift skspritenode sknode

基本卡片对象:

import Foundation
import SpriteKit

class Card: SKSpriteNode {
    var cardValue:Int = 0

    init() {
        cardValue = 10
    }
    ...
}

为什么当它是SKNode的孩子时我无法读取此值?使用lldb进行调试时,它会向我显示整个对象中的值,但我无法访问它:

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

看到输出后,我想我可以试试这个:

(lldb) p handsOnScreen.children[0].cardValue
error: <EXPR>:1:35: error: value of type 'SKNode' has no member 'cardValue'

我做错了什么?

1 个答案:

答案 0 :(得分:2)

您必须将SKNode强制转换为Card才能访问其属性。

if let card = handsOnScreen.children[0] as? Card {
  print(card.cardValue)
}

我使用if let语句而非强制解包(as!)以确保安全,以防children[0]处的对象碰巧不是Card