?? (Nil-Coalescing Operator)
The ?? operator (nil-coalescing operator) in Swift returns a default value when an Optional is nil. It provides a concise way to supply a fallback for Optional values.
Syntax
// Basic form (returns b if a is nil) a ?? b // Chaining (returns the first non-nil value from left to right) a ?? b ?? c // Assignment variable = optionalValue ?? defaultValue
Syntax Overview
| Syntax | Description |
|---|---|
| a ?? b | Returns the value of a if it is not nil; otherwise returns b. |
| a ?? b ?? c | Returns the first non-nil value from left to right (chaining). |
| variable = opt ?? default | Unwraps the Optional and assigns the default value if it is nil. |
| opt ?? { expression }() | Uses a closure on the right-hand side to compute a complex default value. |
Sample Code
// Basic usage
let username: String? = nil
let displayName = username ?? "Guest"
print(displayName) // Guest
// When a value is present
let loggedInUser: String? = "Taro"
let name = loggedInUser ?? "Guest"
print(name) // Taro
// Chaining
let primary: String? = nil
let secondary: String? = nil
let fallback = "Default"
let result = primary ?? secondary ?? fallback
print(result) // Default
// Default value for numbers
let input = "abc"
let number = Int(input) ?? 0 // Falls back to 0 if conversion fails
print(number) // 0
let validInput = "42"
let validNumber = Int(validInput) ?? 0
print(validNumber) // 42
// Default value for dictionaries
let config: [String: Int] = ["timeout": 30]
let timeout = config["timeout"] ?? 60
let retries = config["retries"] ?? 3
print("Timeout: \(timeout)s, Retries: \(retries)")
// Use in assignment
var settings: String? = nil
settings = settings ?? "Default Settings"
print(settings!) // Default Settings
Notes
The ?? operator is a shorthand for the ternary operator. It is equivalent to a != nil ? a! : b internally, but is more readable. The right-hand side is only evaluated when the left-hand side is nil (short-circuit evaluation).
The types on both sides must be compatible. If the type of the right-hand side does not match the wrapped type of the left-hand side Optional, a compile error will occur. Also, note that if you specify an Optional on the right-hand side, the result may itself be an Optional.
For method calls using Optional Chaining, see Optional Chaining / map / flatMap (Optional).
If you find any errors or copyright issues, please contact us.