Page 175

28. Swift – Optional Chaining

Swift

The process of querying, calling properties, subscripts and methods on an optional that may be 'nil' is defined as optional chaining. Optional chaining return two values: 

if the optional contains a 'value' then calling its related property, methods and subscripts returns values

if the optional contains a 'nil' value all its its related property, methods and subscripts returns nil

Since multiple queries to methods, properties and subscripts are grouped together failure to one chain will affect the entire chain and results in 'nil' value.

Optional Chaining as an Alternative to Forced Unwrapping Optional chaining is specified after the optional value with '?' to call a property, method or subscript when the optional value returns some values. Optional Chaining '?'

Access to methods,properties and subscriptsOptional Chaining '!' to force Unwrapping

? is placed after the optional value to call property, method or subscript

! is placed after the optional value to call property, method or subscript to force unwrapping of value

Fails gracefully when the optional is 'nil'

Forced unwrapping triggers a run time error when the optional is 'nil'

Program for Optional Chaining with '!' class ElectionPoll { var candidate: Pollbooth? } class Pollbooth { var name = "MP" }

let cand = ElectionPoll()

let candname = cand.candidate!.name

163

​Quick is just a powerful and spontaneous programming language for macOS, iOS, watchOS and tvO...  

...

Advertisement