Optionals
ln 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
var s:String?
The variable s in Listing 9-1 is declared as an optional, and the starting value is nil.
Forced Unwrapping
If you are sure that an optional has a value, then you can use an exclamation point (!) to unwrap the value. For instance, if you know that s has a value, then you could unwrap s and use the value as shown in Listing 9-2.
Listing 9-2. Unwrapping var s:String?
s = "ABC”
s!