A swift impression of the Swift Tour (2) Optional Values and Control Flow

The concept and usage of optional values are no stranger to JS developers who are used to checking variables that might be undefined or null. However, the Swift way of writing and integrating them into control flows does require some time to get used to.

Declare optional values

Optionals are simply variables that might not have a value, in other words, variables that could possibly hold a value of nil (equivalent to null in JS if the nil value is explicitly assigned, or undefined in JS if the variable is not initialized). The way to mark a variable optional is to append a question mark to its type declaration:

Use optional values

When dealing with an optional, the ?? operator can be used to provide a fallback value:

More common ways to use optional values involve the if let block and the guard let…else block.

The concept of these two are like two sides of a coin. Both first assign the optional value to a constant (declared by the let statement), then execute or not execute the code in the block according to if the value is nil.

In the case of a if let block, the code block gets executed if the optional value is not nil.

In the case of a guard let…else block, which usually works in a function, the code block gets executed if the value is nil. Here it is also expected that the code block terminates the function with a return statement or throws an error.