Nil coalescing

There’s one final and rather handy way to unwrap an optional. You use it when you want to get a value out of the optional no matter what — and in the case of nil, you’ll use a default value. This is called nil coalescing.

Here’s how it works:

var optionalInt: Int? = 10

var mustHaveResult = optionalInt ?? 0

The nil coalescing happens on the second line, with the double question mark (??), known as the nil coalescing operator. This line means mustHaveResult will equal either the value inside optionalInt, or 0 if optionalInt contains nil. In this example, mustHaveResult contains the concrete Int value of 10.

The code above is equivalent to the following:

var optionalInt: Int? = 10 var mustHaveResult: Int

if let unwrapped = optionalInt { mustHaveResult = unwrapped

} else { mustHaveResult = 0

}

Set the optionalInt to nil, like so:

optionalInt = nil

mustHaveResult = optionalInt ?? 0

Now mustHaveResult equals 0.

results matching ""

    No results matching ""