O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Optional Binding

Optional binding is a useful pattern that you can use 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 != ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required