Skip to main content

What does the nil coalescing operator do?

· One min read
Ace the iOS Interview
Aryaman Sharda
Sources & Resources

Main Source: đź”— Ace the iOS Interview

Additional Sources:

Further Reading:

TL/DR

We can use the nil coalescing operator ?? to providea default value in an expression involving an Optional. If the Optional resolves to nil, our default value will be used instead.

var username: String?

// Output: Hello, stranger!
print("Hello, \(username ?? "stranger")!")

username = "@aryamansharda"

// Output: Hello, @aryamansharda!
print("Hello, \(username ?? "stranger")!")