0

I understand that many post errors similar to this, but I feel this is an exceptional circumstance.

As part of a tutorial I am working through the app runs fine for quite sometime, but then for no reason I can work out it crashes with the error

fatal error: unexpectedly found nil while unwrapping an Optional value. The issue is that even if I run the application very slowly it seems to crash on contact of objects and sometimes not (and the app only has 3 objects so it's easy to see what's happening). The function that it breaks on is:

func didBeginContact(contact: SKPhysicsContact) {
    if contact.bodyA.node!.name == "ball" {
        collisionBetweenBall(contact.bodyA.node!, object: contact.bodyB.node!)
    } else if contact.bodyB.node!.name == "ball" {
        collisionBetweenBall(contact.bodyB.node!, object: contact.bodyA.node!)
    }
}

I understand this is only a snippet but does anything spring to mind as to where I should be looking for an error?

Frankeex
  • 449
  • 3
  • 20

1 Answers1

0

The error

fatal error: unexpectedly found nil while unwrapping an Optional value

is because of the values that are forced unwrapped with ! in your code.

If you want to avoid these crashes, you can safely unwrap the values, for example with if let:

func didBeginContact(contact: SKPhysicsContact) {
    if let bodyANode = contact.bodyA.node, let bodyBNode = contact.bodyB.node {
        if bodyANode.name == "ball" {
            collisionBetweenBall(bodyANode, object: bodyBNode)
        } else if bodyBNode.name == "ball" {
            collisionBetweenBall(bodyBNode, object: bodyANode)
        }
    } else {
        print("error, one of the nodes was nil")
    }
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253