Looking for swift Answers? Try Ask4KnowledgeBase
Looking for swift Keywords? Try Ask4Keywords

Swift Language Nil Coalescing Operator


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.