Dilution Calculator - Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Hi, I'm working on a Dilution calculator and I get the error "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"

It was running fine but then I decided to add a "clear button" and that's when the error started.

@IBAction func button(_ sender: Any) {
    self.ContainerSizeTextField.resignFirstResponder()
    self.DilutionRatioTextField.resignFirstResponder()
    
    let firstValue = Double(ContainerSizeTextField.text!)
    let secondValue = Double(DilutionRatioTextField.text!)
    let thirdValue = Double(1)
    
    let outputValue = Double(secondValue! + thirdValue)
    let outputValue1 = Double(firstValue! / outputValue)
    let outputValue2 = Double(firstValue! - outputValue1)
    
    let c:String = String(format:"%.1f", outputValue1)
    let d:String = String(format:"%.1f", outputValue2)
    
    TotalProductLabel.text = " \(c)"
    TotalWaterLabel.text = " \(d)"

}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}
@IBAction func clear(_ sender: Any) {
    
    ContainerSizeTextField.text = " "
    DilutionRatioTextField.text = " "
    TotalProductLabel.text = "0"
    TotalWaterLabel.text = "0"
    

Error happens at "let outputValue = Double(secondValue! + thirdValue)"

I'm able to run the app once before I get the error. Usually after hitting the "clear button".

Accepted Answer

That's because secondValue (as well as firstValue) is nil.

    let firstValue = Double(ContainerSizeTextField.text!)
    let secondValue = Double(DilutionRatioTextField.text!)

If String you use in Double is not a numeric value, then result is nil.

That's the case once you avec reset to "".

Easy way to correct :

    let firstValue = Double(ContainerSizeTextField.text ?? "0") ?? 0.0  // text could also be nil
    let secondValue = Double(DilutionRatioTextField.text ?? "0") ?? 0.0

    let outputValue = Double(secondValue + thirdValue)
    var outputValue1: Double = 0
    if outputValue > 0.00000001 || outputValue < -0.0000000001 { // You should  test outputValue for zero
         outputValue1 = Double(firstValue / outputValue)
    }
    let outputValue2 = Double(firstValue - outputValue1)
Dilution Calculator - Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
 
 
Q