Optional Binding

Optional binding is a useful pattern to detect whether an optional contains a value. If there is a value, you 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 - anOptional is nil
    }

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

Example 9.6. Optional binding
var errorCodeString: String?                               nil
errorCodeString = "404"                                    "404"
if errorCodeString != nil {
    let theError = errorCodeString!
if let theError = errorCodeString ...

Get Swift Programming: The Big Nerd Ranch Guide, 3rd Edition 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.