O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

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 chaining

Optional chaining allows us to call properties, methods, and subscripts on an optional that might be nil. If any of the chained values return nil, the return value will be nil. The following code gives an example of optional chaining using a fictitious car object. In this example, if either the car or tires optional variables are nil, the variable tireSize will be nil, otherwise the tireSize variable will be equal to the tireSize property:

var tireSize = car?.tires?.tireSize 

The following Playground illustrates the three ways of verifying whether an optional contains a valid value prior to using it:

In the preceding Playground, ...

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