Skip to content

iOS double question marks in Swift ??

Platform Language License

?? is Nil-Coalescing Operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type.

Example:

a != nil ? a! : b

The shorthand code is

a ?? b

var aValue: Int? //aValue has no value
let bValue = 5
var resultValue: Int
resultValue = aValue ?? bValue
print(resultValue)

//resultValue will be 5

var aValue: Int? = 10 //aValue has value
let bValue = 5
var resultValue: Int
resultValue = aValue ?? bValue
print(resultValue)

//resultValue will be 10

Let's grow together 🌱

Cheers 🍻