OperatorSwift

    ??(_:_:)

    Performs a nil-coalescing operation, returning the wrapped value of an Optional instance or a default Optional value.

    func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T?) rethrows -> T?

    Parameters

    optional

    An optional value.

    defaultValue

    A value to use as a default. defaultValue and optional have the same type.

    Overview

    A nil-coalescing operation unwraps the left-hand side if it has a value, or returns the right-hand side as a default. The result of this operation will be the same type as its arguments.

    This operator uses short-circuit evaluation: optional is checked first, and defaultValue is evaluated only if optional is nil. For example:

    let goodNumber = Int("100") ?? Int("42")
    print(goodNumber)
    // Prints "Optional(100)"
    
    let notSoGoodNumber = Int("invalid-input") ?? Int("42")
    print(notSoGoodNumber)
    // Prints "Optional(42)"

    In this example, goodNumber is assigned a value of 100 because Int("100") succeeds in returning a non-nil result. When notSoGoodNumber is initialized, Int("invalid-input") fails and returns nil, and so Int("42") is called to supply a default value.

    Because the result of this nil-coalescing operation is itself an optional value, you can chain default values by using ?? multiple times. The first optional value that isn’t nil stops the chain and becomes the result of the whole expression. The next example tries to find the correct text for a greeting in two separate dictionaries before falling back to a static default.

    let greeting = userPrefs[greetingKey] ??
        defaults[greetingKey] ?? "Greetings!"

    If userPrefs[greetingKey] has a value, that value is assigned to greeting. If not, any value in defaults[greetingKey] will succeed, and if not that, greeting will be set to the non-optional default value, "Greetings!".