Optionals: Optional Binding

Can be used with if and while statements to check for a value inside an optional, and to extract that value into a constant or variable, as part of a single action.

If let actualNumber = Int(possibleNumber) {
    print("The string \"\(possibleNumber)\" has an integer value of \(actualNumber)")
} else {
    print("The string \"\(possibleNumber)\" could not be converted to an integer")
}
// Prints "The string "123" has an integer value of 123"

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

You can use both constants and variables.

Optionals: Optional Binding — Structure map

Clickable & Draggable!

Optionals: Optional Binding — Related pages: