In situations where you can’t be sure a variable has a value present, you can use optionals. An optional is a variable that can have either an assigned value or no value at all. Using optionals is an alternative to setting objects to nil. Optionals can be used with any type in Swift including numbers, strings, and objects.
You declare optionals like variables or constants, but you must include a ? after the type declaration (see Listing 9-1). Like variables and constants, the data type of an optional may be inferred.
Listing 9-1. String Optional Declaration
The variable s in Listing 9-1 is declared as an optional, and the starting value is nil.
If you are sure that an optional has a value, ...