Swift Language Optionals Nil Coalescing Operator

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

You can use the nil coalescing operator to unwrap a value if it is non-nil, otherwise provide a different value:

func fallbackIfNil(str: String?) -> String {
    return str ?? "Fallback String"
}
print(fallbackIfNil("Hi")) // Prints "Hi"
print(fallbackIfNil(nil)) // Prints "Fallback String"

This operator is able to short-circuit, meaning that if the left operand is non-nil, the right operand will not be evaluated:

func someExpensiveComputation() -> String { ... }

var foo : String? = "a string"
let str = foo ?? someExpensiveComputation()

In this example, as foo is non-nil, someExpensiveComputation() will not be called.

You can also chain multiple nil coalescing statements together:

var foo : String?
var bar : String?

let baz = foo ?? bar ?? "fallback string"

In this example baz will be assigned the unwrapped value of foo if it is non-nil, otherwise it will be assigned the unwrapped value of bar if it is non-nil, otherwise it will be assigned the fallback value.



Got any Swift Language Question?