Swift Language Conditionals Nil-Coalescing Operator


Example

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

The nil-coalescing operator is shorthand for the code below that uses a ternary operator:

a != nil ? a! : b

this can be verified by the code below:

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

Time For An Example

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

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

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