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:

i​f​ ​l​e​t​ ​t​e​m​p​o​r​a​r​y​C​o​n​s​t​a​n​t​ ​=​ ​a​n​O​p​t​i​o​n​a​l​ ​{​
 ​ ​ ​ ​/​/​ ​D​o​ ​s​o​m​e​t​h​i​n​g​ ​w​i​t​h​ ​t​e​m​p​o​r​a​r​y​C​o​n​s​t​a​n​t​
 ​}​ ​e​l​s​e​ ​{​
 ​ ​ ​ ​/​/​ ​T​h​e​r​e​ ​w​a​s​ ​n​o​ ​v​a​l​u​e​ ​i​n​ ​a​n​O​p​t​i​o​n​a​l​;​ ​i​.​e​.​,​ ​a​n​O​p​t​i​o​n​a​l​ ​i​s​ ​n​i​l​

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

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.