Swift Nil Coalescing
Nil coalescing is giving an optional a fallback value to use when it holds nil. A held value wins, and nil takes the fallback instead.
A fallback beside a real value
The first optional holds nil, so the fallback prints. The second holds a name, so the name prints.
let missing: String? = nil
let present: String? = "Sam"
print(missing ?? "guest")
print(present ?? "guest")Chaining into a method
The chain reaches uppercased through the held value. The ?? part settles the result as a plain string.
let name: String? = "ana"
print(name?.uppercased() ?? "unknown")A chain that lands on nil
This optional holds nil, so the chain reaches nothing. The fallback prints instead.
let name: String? = nil
print(name?.uppercased() ?? "unknown")Chaining into a count
The chain reads the count of the held word. The fallback 0 stands ready if the optional holds nil.
let word: String? = "Swift"
print(word?.count ?? 0)Example
let first: String? = "lee"
let second: String? = nil
print(first ?? "anon")
print(second ?? "anon")
print(first?.uppercased() ?? "unknown")
print(second?.uppercased() ?? "unknown")Key points
- The ?? operator reads the optional on its left side.
- A held value on the left becomes the result, as a plain value.
- A nil on the left makes the right side the result.
- A question mark and dot, written ?., reaches a member only when a value is held.
- A chain that lands on nil can settle with ?? and a fallback.
In this example, the first optional holds lee and the second holds nil. The third line prints lee, because the held value wins over the fallback. The fourth line prints anon, because nil takes the fallback. The fifth line chains into uppercased and prints LEE. The last line chains from nil, lands on nil, and prints the fallback unknown.
Note
The fallback and the held value must share the same type.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Swift Compiler
Exercise
What does this print? let city: String? = nil, then print(city ?? "Rome")