Swift has optional types for operations that may fail. An array index like airports["XYZ"]
is an example of this. It will fail if the index is not found. This is in lieu of a nil
type or exception.
The simplest way to unwrap an optional type is to use an exclamation point, like so: airports["XYZ"]!
. This will cause a panic if the value is nil
.
Here's some further reading.
You can chain methods on option types in Swift, which will early exit to a nil
without calling a method if the lefthand value is nil
. It works when you insert a question mark between the value and method like this: airports["XYZ"]?.Method()
. Because the value is nil
, Method()
is never called. This allows you to delay the decision about whether to deal with an optional type, and can clean up your code a bit.
To safely use an optional type without panicking, just provide an alternate path using an if
statement.
if let x:String? = airports["XYZ"] {
println(x!)
} else {
println("airport not found")
}