Optional Binding

Optional binding is a useful pattern to detect whether an optional contains a value. If there is a value, then you can assign it to a temporary constant or variable and make it available within a conditional’s first branch of execution. This can make your code more concise while also retaining its expressive nature. Here is the basic syntax:

if let temporaryConstant = anOptional {
    // Do something with temporaryConstant
 } else {
    // There was no value in anOptional; i.e., anOptional is nil
}

With this syntax in hand, refactor the example above to make use of optional binding.

Listing 8.5  Optional binding

import Cocoa

var errorCodeString: String?
errorCodeString = "404"
if errorCodeString != nil {
    let theError ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.