1

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.

@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 {

    }

}
pnuts
  • 58,317
  • 11
  • 87
  • 139
DevelUpGames
  • 139
  • 1
  • 14

1 Answers1

2

“fatal error: unexpectedly found nil while unwrapping an Optional value"

This happens when the Optional doesn't have any value.

What you need to do is check that the variable is not nil before you unwrap it.

For example, assumming ageInt is the Optional with the nil value:

if ageInt != nil {
    // Do Something
}

Or safely unwrapping the value with an if let statement:

if let safeAgeInt = ageInt {
   // Do Something with safeAgeInt
}
Esteban Herrera
  • 2,263
  • 2
  • 23
  • 32