What does the nil coalescing operator do?
· One min read
Sources & Resources
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")!")