2

If the following code runs

var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

print(airports["YYZ"])

Why does the console print

Optional("Toronto Pearson")

Why does it print Optional( withValue ) and not just the value?

Why would I need to know that in the console?

SoEzPz
  • 14,958
  • 8
  • 61
  • 64
  • If the console only printed the value, how would you be able to tell the difference between a String type and an Optional type? – 7stud Jul 25 '15 at 05:34

1 Answers1

4

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")
}
lunixbochs
  • 21,757
  • 2
  • 39
  • 47
  • This is an even better explanation than my answer. +1 – Kyle Emmanuel Jul 25 '15 at 04:05
  • 2
    That's not a normal unwrapping, but a _forced unwrapping_, which causes the app to crash if the key is not found. That should explicitly be said in the answer, providing an alternate path (such as optional binding) for a safer way to achieve the same result – Antonio Jul 25 '15 at 05:54
  • Thanks, I should have been more clear initially. Updated. – lunixbochs Jul 25 '15 at 19:45