All Articles

The double question marks in Swift ??

The ?? in Swift is called the “nil-coalescing operator”. Let’s break that down:

  • “nil” – a value which represents the absence of a value, in other words – nothing
  • “coalescing” – to combine or to merge
  • “operator” – a character that represents an action; it tells the compiler to perform an operation, such as “+” (add) or “-” (subtract)

According to the Apple documentation:

“The 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. The expression b must match the type that is stored inside a.”

Let’s look at some examples below.

Example 1:

var anOptional: Int?
let aValue = 5
var theResult: Int

theResult = anOptional ?? aValue

print(theResult)
//theResult will be 5

Basically, what this is saying is that:

Is anOptional nil? If yes, use aValue. If anOptional does contain a value, unwrap it, and use the unwrapped anOptional.

Example 2:

var anOptionalWithValue: Int? = 28
let aValue = 13
var theResult: Int

theResult = anOptionalWithValue ?? aValue

print(theResult)
//theResult will print 28