Swift - Data Type Optional chaining

Introduction

Optional chaining is an alternative to unwrapping your optional variables for these situations.

You use the ? operator after an optional variable to use it as if it were not optional.

If a nil is encountered, the call will fail and return nil instead of crashing.

Demo

var optionalArray  : [Int]? = [1,2,3,4] 
var count = optionalArray?.count 
print(count)

If you change the array to be nil, count is nil:

var optionalArray  : [Int]? = [1,2,3,4] 
optionalArray = nil 
count = optionalArray?.count 
print(count)

You can chain multiple optionals together and if any of them are nil the statement ends:

Demo

let optionalDict  : [String  : [Int]]? = ["array":[1,2,3,4]] 
var count = optionalDict?["array"]?.count 
print(count)

Related Topic