Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fatal error: unexpectedly found nil while unwrapping an Optional value [duplicate]

Tags:

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") } } 
like image 868
Arshia Avatar asked Jul 25 '14 04:07

Arshia


1 Answers

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.

like image 50
jmduke Avatar answered Oct 07 '22 20:10

jmduke