Nil-Coalescing Operator

suggest change

The nil-coalescing operator <OPTIONAL> ?? <DEFAULT VALUE> unwraps the <OPTIONAL> if it contains a value, or returns <DEFAULT VALUE> if it is nil. <OPTIONAL> is always of an optional type. <DEFAULT VALUE> must match the type stored inside <OPTIONAL>.

The nil-coalescing operator is shorthand for this ternary expression:

a != nil ? a! : b

This comparison shows that the two forms match:

(a ?? b) == (a != nil ? a! : b) // outputs true

Time For An Example

let defaultSpeed:String = "Slow"
var userEnteredSpeed:String? = nil

print(userEnteredSpeed ?? defaultSpeed) // outputs "Slow"

userEnteredSpeed = "Fast"
print(userEnteredSpeed ?? defaultSpeed) // outputs "Fast"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents