Nil-Coalescing Operator
suggest changeThe 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"
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents