Tim Tim - 5 months ago 12
Swift Question

"if let" statement executed despite value being nil

I have an "if let" statement that is being executed, despite the "let" part being nil.

if let leftInc : Double? = self.analysis.inputs[self.btnLeftIncisor.dictionaryKey!]! {
let valueString : String = formatter.stringFromNumber(NSNumber(double: leftInc!))!
self.leftIncisorTextField?.text = valueString
self.btnLeftIncisor.associatedLabel?.text = valueString

// self.analysis.inputs is a Dictionary<String, Double?>

The inputs dictionary holds information entered by the user - either a number, or nil if they haven't entered anything in the matching field yet.

Under the previous version of Swift, the code was written as this:

if let leftInc : Double? = self.analysis.inputs[self.btnLeftIncisor.dictionaryKey!]?? {

and worked correctly.

I saw a similar question here, but in that instance the problem seemed to be the result of using
, which is not the case here.


In your if let you define another optional, that's why nil is a legitimate case. if let is intended mainly to extract (maybe) non optional value from an optional. You might try:

if let leftInc : Double = self.analysis.inputs[self.btnLeftIncisor.dictionaryKey!] {
   // leftInc is not an optional in this scope