Python "or" equivalent in Swift?

Thanks to Swift's cool behavior, I was looking for an equivalent orin Swift.

Something like that:

variable = value or default

I encoded mine :

func |<T>(a:T?, b:T) -> T {
    if let a = a {
        return a
    }
    return b
}

But I was wondering if there is any default implementation in Swift?

Edit: Thanks to the answers, I found the link in the Swift book:

Nil coalescing operator

The nil ( a ?? b) join operator expands the optional parameter a if it contains a value, or returns the default value bif anil is equal. An expression aalways has an optional type. The expression bmust match the type that is stored inside a.

The nil coalescing operator is short for the code below:

    a != nil ? a! : b

(a!) , a, a nil b . nil . ()

+4
2

??:

var optional:String?
var defaultValue:String = "VALUE"

var myString:String = optional ?? defaultValue

print(myString)
+5

nil

let variable = optional ?? default
+4

All Articles