Swift unexpectedly found nil while unwrapping an Optional value on let variable

Hello. I am fairly new to iOS development. I can’t figure out what I am doing wrong for the life of me. I am getting the “Thread 1: EXC_BAD_INSTRUCTION (code=EXC_l386_NVOP, subcode=0x0)” error with the menCalories variable. In the debugger I am getting the error: “fatal error: unexpectedly found nil while unwrapping an Optional value"

Here is my code. Any help would be very much appreciated. Thank you.


    @IBAction func calculate(sender: AnyObject) {
       
        var ageInt:Int? = age.text!.toInt()
        var weightInt:Int? = weightLabel.text!.toInt()
        var heightInt:Int? = height.text!.toInt()
       
        if gender.selectedSegmentIndex == 0 {
       
            let menCalories:Double = 66.47 + (13.75 * Double(weightInt!)) + (5.0 * Double(heightInt!)) - (6.75 * Double(ageInt!))
           
            calories.text = "\(menCalories)"
           
        }
       
        if gender.selectedSegmentIndex == 1 {
           
           
        }
       
    }

This code fails to take into account the person's microbiome, and gender is a spectrum, not an enumeration. The numbers are nonsense.


As for the compilcation error, I assume that one or more of your labels' text isn't an integer.

Jessy is correct.


To be more explicit in regard to the error, "Double(weightInt!)", for example, will fail if weIghtInt is an optional with no value returned from weightLabel.text!.toInt(), which will happen if that text value cannot be converted to an integer. You should be checking for and responding to this case where appropriate.


I suggest rereading the Swift guide regarding Optionals and explicit unwrapping.

https://negibi.com bir incele derim.

Swift unexpectedly found nil while unwrapping an Optional value on let variable
 
 
Q