Unwrapping an optional
There are multiple ways to unwrap an optional. All of them essentially assert that there is truly a value within the optional. This is a wonderful safety feature of Swift. The compiler forces you to consider the possibility that an optional lacks any value at all. In other languages, this is a very commonly overlooked scenario that can cause obscure bugs.
Optional binding
The safest way to unwrap an optional is using something called optional binding. With this technique, you can assign a temporary constant or variable to the value contained within the optional. This process is contained within an if
statement, so that you can use an else
statement for when there is no value. An optional binding looks like this:
if let string = possibleString { println("possibleString has a value: \(string)") } else { println("possibleString has no value") }
An optional binding is distinguished from an if
statement primarily by the if let
syntax. Semantically...