Nil Value on "If Let" Statement

I was using an if-let statement to assign a variable a value only if the corresponding text field was not empty.

var AB: Double? {
    if let abText = sideAB.text, ab = Double(abText) {
          return ab
    } else {
          return nil
    }
}

However, I received the error message

fatal error: unexpectedly found nil while unwrapping an Optional value.

I thought "if-let" statements prevented this, so why did it still happen and how can I stop it from happening?

Accepted Answer

I'm not sure you can chain those two initialization expressions together like that. I think what's going on is that instead of stopping after failing to initialize abText, it continues on and attempts the following expression. Try rewriting it like this, using the ?? operator: if sideAB.text ends up nil, an empty string will get swapped in to prevent a fatal error, but because Double(" ") returns nil, you still get the desired behavior.

var AB: Double? {
     return Double(sideAB.text ?? "")
}

Thank you! This helps 🙂

Glad to hear it. Yeah, as soon as I discovered that ?? operator it made my life a lot easier.

The form of your 'if' is OK, though I think it's clearer to repeat the "let":


if let abText = sideAB.text, let ab = Double(abText)


Instead, I think you're just mistaken which optional is being unwrapped. My guess is that either 'sideAB' is an implicitly unwrapped optional that's actually nil, or the error comes from the caller's use of an AB return value of nil.


For example, I can get the error message in a playground like this:


import UIKit

var sideAB: UILabel! = nil

var AB: Double? {
  if let abText = sideAB.text, let ab = Double(abText) {
  return ab
  } else {
  return nil
  }
}

print (AB)


You can fix that with:


if let abText = sideAB?.text, …
Nil Value on "If Let" Statement
 
 
Q