-3

I get the error for the line of code here:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    hero.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 300))
}

I'm quite new to code and I am having trouble working out why I am getting this error.

aaron
  • 39,695
  • 6
  • 46
  • 102
Nemo
  • 3
  • 2
  • Show the declaration of `hero`. – matt Nov 05 '17 at 02:16
  • If it's failing at that line, then (a) `hero` is likely an implicitly unwrapped optional; and (b) it's `nil`. If this is the case, we then need to see not only how you declared it, but how you instantiated it, too. – Rob Nov 05 '17 at 04:38
  • Try to put hero?.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 300)) if the problem is with hero. If it's not crashing tha't the case. If crashing there is something else. – Arrabidas92 Nov 05 '17 at 15:51
  • @Arrabidas92 he would need also to change the declaration from IUO to optional – Leo Dabus Nov 05 '17 at 15:53
  • @LeoDabus what is IUO ? – Arrabidas92 Nov 05 '17 at 16:11
  • @Arrabidas92 implicitly unwrapped optional – Leo Dabus Nov 05 '17 at 16:14
  • @LeoDabus Ah okay ! Yes you are right for the declaration. – Arrabidas92 Nov 05 '17 at 16:19
  • Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Joachim Sauer Oct 23 '19 at 14:18

1 Answers1

-4

physicsBody is probably nil, you can test for nil

if hero.physicsBody != nil {
    hero.physicsBody!.applyImplulse(CGVector(dx: 0, dy: 300))
}else {
    //do whatever should be done when there is no physicsBody
}

there could be other issues but that is all that I can suggest without knowing more about your program

if you don't know what I mean by nil, I suggest reading more about optional data types What is an optional value in Swift?

C1FR1
  • 133
  • 1
  • 9
  • Thank you so much for your reply, I will definitely re-submerge myself into understanding optionals! – Nemo Nov 05 '17 at 01:56
  • 1
    @Nemo This line it isn't the source of your problem. You are using optional chaining so your method applyImpulse will never be called if physicsBody is nil. Your code would fail silently. – Leo Dabus Nov 05 '17 at 02:05