Nil-coalescing operator

Sergey Chsherbak
3 min readJan 28, 2023

The use of optionals in Swift is one of its most powerful features, as it guarantees the safety of your program. However, optionals can also make your code difficult to read and write as they must be unwrapped in a safe manner.

Explicitly unwrapped optionals or why do we need a nil-coalescing operator?

One of the ways to unwrap an optional is by using the ! operator after a variable. Consider this example:

let number: Int? = 1
let unwrappedNumber = number!

This way of unwrapping an optional is called force unwrapping. While you can use it to remove the optionality of a variable, it also introduces a risk to your program by terminating it if the variable has no value.

You have to think several times before using it because if it crashes your program at any point, your users will not be pleased with that experience.

What is the nil-coalescing operator?

This is an alternative way of unwrapping an optional and providing a default value if it is not present. The nil-coalescing operator provides a more neat and simple way of conditional checking and unwrapping making the code clearer and more readable. It really saves the day!

Let’s take a look at this example:

let number: Int? = 1
print(number) // Prints 'Optional(1)'

This is a constant named number that contains either an integer or nil. If you try to print it you might expect to see 1, but you will see Optional(1), which is probably not what you would want to see.

Here we can actually benefit from the nil-coalescing operator since it not only unwraps the value but also provides a default one if it is nil.

The nil-coalescing operator is written as two question marks — ??. As a result, if the left-most operand contains a value, it returns the result of the left-most operand, otherwise, it returns the result of the right-most operand.

You could end up writing these lines of code:

let number: Int? = 1
let result = number ?? 0
print(result) // Prints '1'

This will print 1, thanks to the nil-coalescing operator. It also means that the result guarantees us to return a value of type Int, either a real value or a default one.

It is also important to emphasize that the default value must match the type that is stored inside the variable.

If you wish to see the default value printed instead, try writing this:

let number: Int? = nil
let defaultNumber = 0
let result = number ?? defaultNumber
print(result) // Prints '0'

Now this will print 0 because the default value is used instead.

Conclusion

As you can imagine, the nil-coalescing operator is quite useful to make sure you have appropriate values before using them. Moreover, it is an excellent tool for removing unnecessary optionality from the code, making it more readable and comprehensible.

--

--

Sergey Chsherbak

iOS Engineer based in Copenhagen. Writing about Swift for fun. Working with Swift for food.