SLN SLN - 5 months ago 9
Swift Question

Optional Binding, what exactly the word "Binding" means here?

Optional binding is a method to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable.

var possibleNumber: Int? = 123

if let actualNumber = Int(possibleNumber){
print("\"possibleNumber\" has an integer value of \(actualNumber)")
} else {
print("\"possibleNumber\" could not be converted to an integer")
}


Question Does the Binding mean the action of assigning the valid value into the temporary constant/variable? I.e. "binding" those two things together?

Answer

Does the Binding mean the action of assigning the valid value into the temporary constant/variable? I.e. "binding" those two things together?

Yes. Basically, assignment of a value to a variable name is a binding — it "binds" the name to the value. So even this is a binding:

let x = 1

What's special with if let is that the binding takes place only if the value is an Optional that can be safely unwrapped (that is, it is not nil). If it can't be unwrapped safely, it is not unwrapped and no binding takes place (and the if condition fails).