O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The Nil Coalescing Operator

A common operation when dealing with optionals is to either get the value (if the optional contains a value) or to use some default value if the optional is nil. For example, when pulling out the error information inside of errorDescription, you might want to default to "No error" if the string does not contain an error. You could accomplish this with optional binding.

Listing 8.11 Using optional binding to parse errorDescription

...
let description: String
if let errorDescription = errorDescription {
    description = errorDescription
} else {
    description = "No error"
}

There is a problem with this technique. You had to write a lot of code for what should be a simple operation: Get the value from ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required