简体   繁体   中英

Xcode console error message: 'fatal error: unexpectedly found nil while unwrapping an Optional value' (Swift)

I am working on a BMICalculator. I can't seem to find any optional value here. I chose a number pad as the keyboard so that only numbers could be entered.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let results = segue.destinationViewController as? ResultsController {

        if let height = Double(heightTextField.text!), weight = Double(weightTextField.text!) {
            let info = BMIInformation(cm: height, kg: weight)
            let bmi = String(info.computeBMI())
            results.bmiValue.text = bmi
        }
    }

}

Here is my results controller class:

class ResultsController: UIViewController {

    @IBOutlet weak var bmiValue: UILabel!
    @IBOutlet weak var bmiDescription: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

heightTextField.text! probably doesn't have a value when you try to force unwrap it

Since you don't know which line is throwing the crash, so my guess is it can be

heightTextField.text!

Just use it like this instead

(heightTextField?.text)!

Reason: I am considering you have an outlet of heightTextField and it must look something like this

@IBOutlet weak var heightTextField: UITextField!

Now the exclamation at the end of this line means the variable is expecting a value and it cannot be nil, now see if this is connected to your storyboard. If not, then it will get nil. Hence crash.

Putting a ? in (heightTextField?.text)!, when using this variable asks the compiler that even if the variable will get nil it won't crash. But it won't give the text you might have enetered in your textfield either. So please check the connectivity of your IBOutlet.

If this is not reason for crash then please add a swift and All exceptions breakpoint and try to find the place of crash. It will be easier to explain then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM