The Nil Coalescing Operator

A common operation when dealing with optionals is to either get the value (if the optional contains 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 errorCodeString

...
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 the ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.