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, we begin by defining the optional string variable, stringOne. We then explicitly check for nil by using the != (not equal to) operator. If stringOne is not equal to nil, we print the value of stringOne to the console. If stringOne is nil, we print the Explicit Check: stringOne is nil message to the console. As we can see in the results console, Explicit Check: stringOne is nil is printed to the console because we have not assigned a value to stringOne yet.

When an optional value is defined without giving it a value, it is the same as setting its initial value to nil.

We then use optional binding to verify that stringOne is not nil. If stringOne is not nil, the value of stringOne is put into the tmp temporary variable, and we print the value of tmp to the console. If stringOne is nil, we print the Optional Binding: stringOne is nil message to the console. As we can see in the results console, Optional Binding: stringOne is nil is printed to the console because we have not assigned a value to stringOne yet.

We use optional chaining to assign the value of the count property of the stringOne variable to the charCount1 variable if stringOne is not nil. The charCount1 variable is nil because we have not yet assigned a value to stringOne.

We then assign a value of http://www.packtpub.com/all to the stringOne variable and rerun all three tests again. This time, stringOne has a non-nil value; therefore, the value of charCount2 is printed to the console.

It would be tempting to say that I need to set this variable to nil and define it as optional, but that would be a mistake. The mindset regarding optionals should be to only use them if there is a specific reason for the variable to have a nil value.

We will be discussing optionals is much greater detail in Chapter 10, Using Optional Types.