I am trying to run this code but I keep on getting this error:
fatal error: unexpectedly found nil while unwrapping an Optional value
I don't understand what it means or why I'm getting it. Any hint?
import UIKit class ViewController: UIViewController { var lastNumber: String = "" @IBOutlet var answerField: UILabel @IBOutlet var operaterLabel: UILabel override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func buttonTapped(theButton: UIButton) { if answerField.text == "0" { answerField.text = theButton.titleLabel.text } else { answerField.text = answerField.text + theButton.titleLabel.text } } @IBAction func plusTapped(theButton: UIButton) { // error is talking about the next line if operaterLabel.text == "" { operaterLabel.text = "+" lastNumber = answerField.text answerField.text = "0" } else { enterTapped(nil) operaterLabel.text = "+" } } @IBAction func minusTapped(theButton: UIButton) { if operaterLabel.text == "" { operaterLabel.text = "-" lastNumber = answerField.text answerField.text = "0" } else { enterTapped(nil) operaterLabel.text = "-" } } @IBAction func clearTapped(AnyObject) { answerField.text = "0" operaterLabel.text = "" lastNumber = "" } @IBAction func enterTapped(AnyObject?) { var num1 = lastNumber.toInt() var num2 = answerField.text.toInt() if !num1 || !num2 { showError() return } var answer = 0 if operaterLabel.text == "-" { var answer = num1! - num2! } else if operaterLabel.text == "+" { var answer = num1! + num2! } else { showError() return } answerField.text = "\(answer)" } func showError() { println("Ther was an error") } }
the error refers to the fact that you're accessing the parameter of an optional value when the optional value is set to nil (e.g. accessing answerField.text
when answerField
is nil), likely one of your two UILabels
.
If the line operaterLabel.text == ""
is throwing the exception, then your operaterLabel
is nil. Verify that you have connected it successfully to the label in your Interface Builder file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With