O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

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

The nil coalescing operator is similar to the ternary operator that we discussed in Chapter 2, Learning About Variables, Constants, Strings, and Operators. The ternary operator assigns a value to a variable, based on the evaluation of a comparison operator or a Boolean value. The nil coalescing operator attempts to unwrap an optional, and if it contains a value, it will return that value, or a default value if the optional is nil.

Let's look at a prototype for the nil coalescing operator:

optionalA ?? defaultValue 

In this example, we demonstrate the nil coalescing operator when the optional contains a nil and also when it contains a value:

var defaultName = "Jon" var optionalA: String? var optionalB: String? optionalB ...

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