Nil-Coalescing Operator
Don’t be confused by the “??”—we’re not asking a question here. Today, we’re going to study the ??
operator.
This is a super common operator that many developers use without knowing its official name. But even a mere operator deserves to be called by its true name so that it can “bloom” into something useful (as a literature major might say).
1. What is the Nil-Coalescing Operator?
When you use this operator, you no longer need to check whether an optional type contains a value before extracting it.
Here’s the basic syntax:
let result = optionalValue ?? defaultValue
Doesn’t make much sense without an example, right? Let’s take a look at how it works.
Suppose we have an optional string called name
:
var name: String? = nil
Now, we want to print:
hello, \(name)
ifname
contains a valuehello, what's your name?
ifname
isnil
With optional binding, you would write something like this:
if let name = name {
print("hello, \(name)")
} else {
print("hello, what's your name?")
}
But with Nil-Coalescing, it simplifies to:
print("hello, \(name ?? "what's your name?")")
One line! So simple, right?
How Does It Work?
① If name
contains a value:
let message = "hello, \(name ?? "what's your name?")"
Will output:
hello, John
② If name
is nil
, the expression evaluates to the default value:
let message = "hello, \(name ?? "what's your name?")"
Will output:
hello, what's your name?
The right-hand side operand ("what's your name?"
) is used as a default value in case name
is nil
.
Important Notes:
The optional type on the left-hand side and the non-optional type on the right-hand side must be of the same type, excluding the optionality.
Examples:
Optional String ?? Non-Optional String
(Valid ✅)Optional String ?? Non-Optional Int
(Invalid ❌)
It’s a bit like a ternary operator, right? Since it’s so easy, there’s no need for further explanation!
That’s it for the Nil-Coalescing Operator! Keep it simple and use this operator whenever you want to safely provide a default value for an optional type.