Michael
Michael

Reputation: 1

How to prevent crashing when tapping off a node

The code that I am writing has a problem where whenever I tap somewhere other than a node (ex. background) the app ends up crashing.

I've tried making an if let statement but it says I can't downcast a SKnode to a more optional type SKSpriteNode. I've also tried 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)

        }
    }

Tapping on anything other than the SKSpriteNodes that are considered objects results in a SIGABRT.

Upvotes: 0

Views: 33

Answers (1)

Marwen Doukh
Marwen Doukh

Reputation: 2050

The app crashes because you are force unwrapping a value in this line:

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

So instead, use:

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)

}

Always try to avoid the force unwrapping (as!). Use Optional Chaining instead.

Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil.

Upvotes: 0

Related Questions