分接节点时如何防止崩溃

时间:2019-05-15 13:37:11

标签: swift xcode sprite-kit

我正在编写的代码存在一个问题,即每当我点击节点以外的其他位置(例如背景)时,应用都会崩溃。

我尝试制作一个if let语句,但是它说我不能将SKnode转换为更可选的类型SKSpriteNode。  我也尝试过if node.contains(position of touch)

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    if let touchLocation = touch?.location(in: self) {
    let selectedNode = nodes(at: touchLocation)[0] as! SKSpriteNode

        activeObject = selectedNode
        storedData = Array(activeObject.name!)
        let platformStoredInt = storedData[2]
        storedPlatform = Int(platformStoredInt.unicodeScalars.first!.value - Unicode.Scalar("0")!.value)

        }
    }

点击除SKSpriteNodes之外的其他对象都将导致SIGABRT。

1 个答案:

答案 0 :(得分:0)

由于您在此行中强制解开值而导致应用崩溃:

let selectedNode = nodes(at: touchLocation)[0] as! SKSpriteNode

因此,请使用:

if let selectedNode = nodes(at: touchLocation)[0] as? SKSpriteNode {

  activeObject = selectedNode
  storedData = Array(activeObject.name!)
  let platformStoredInt = storedData[2]
   storedPlatform = Int(platformStoredInt.unicodeScalars.first!.value - Unicode.Scalar("0")!.value)

}

始终尝试避免强制展开(如!)。请改用Optional Chaining

  

可选链接是一个查询和调用当前可能为零的可选属性,方法和下标的过程。

相关问题