December 2015
Intermediate to advanced
400 pages
13h 3m
English
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 ...
Read now
Unlock full access