-1
class ViewController: UIViewController {
    @IBOutlet weak var label: UILabel!

    var userIsInTheMiddleOfTypingNumber: Bool = false

    @IBAction func appendDigit(sender: UIButton) {
        let digit = sender.currentTitle!

        if (userIsInTheMiddleOfTypingNumber) {
            label.text = label.text! + digit
        }
        else {
            label.text = digit
            userIsInTheMiddleOfTypingNumber = true
        }
    }
}

I am currently creating a calculator app. For some reason, when I run the simulator and try to input some digits in, the siumulator freezes, and the error of bad_instruction appears on the line:

label.text = digit

How would I fix this situation?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
hwhong
  • 23
  • 7
  • Can you post the whole error log ? – Chajmz May 06 '16 at 16:31
  • Is "digit" a string? – Echizzle May 06 '16 at 16:41
  • 2
    To learn how to debug a crash, please see http://www.raywenderlich.com/10209/my-app-crashed-now-what-part-1 – rmaddy May 06 '16 at 16:46
  • If this is an "unexpectedly found nil" crash – then also see [this extensive Q&A](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) on the error. – Hamish May 06 '16 at 16:48

2 Answers2

1

Looks like you forgot to connect the label in the Storyboard with the outlet.

dasdom
  • 13,975
  • 2
  • 47
  • 58
1

Looks like the currentTitle property is nil which results in a crash. You are force unwrapping the property without any nil check.

@IBAction func appendDigit(sender: UIButton) {
    if let digit = sender.currentTitle {
        if (userIsInTheMiddleOfTypingNumber) {
            label.text = label.text! + digit
        }
        else {
            label.text = digit
            userIsInTheMiddleOfTypingNumber = true
        }
    }
}

OR

It could be the reason specified by @dasdom

R P
  • 1,173
  • 2
  • 11
  • 20