The nil coalescing operator helps you provide a default value when something might be missing (nil). It makes your code safer and easier to read.
Nil coalescing operator deep usage in Swift
optionalValue ?? defaultValue
The operator is written as two question marks: ??.
If optionalValue is not nil, it returns that value; otherwise, it returns defaultValue.
name is nil, displayName becomes "Guest".let name: String? = nil let displayName = name ?? "Guest"
let first: String? = nil let second: String? = "Hello" let message = first ?? second ?? "No greeting"
let number: Int? = nil let result = (number ?? 0) + 10
This program tries to greet the user. It first checks userInput, then defaultGreeting, and finally uses a hardcoded fallback.
import Foundation // Optional user input let userInput: String? = nil // Optional default greeting let defaultGreeting: String? = "Hello, friend!" // Use nil coalescing to pick the first non-nil greeting let greeting = userInput ?? defaultGreeting ?? "Hi there!" print(greeting)
You can chain multiple nil coalescing operators to check several optionals in order.
The right side of ?? is only evaluated if the left side is nil, which can save work.
Use parentheses if you combine nil coalescing with other operators to keep code clear.
The nil coalescing operator ?? provides a simple way to use default values for optionals.
It helps avoid long if-let or guard statements by making code shorter and clearer.
You can chain multiple ?? operators to pick the first non-nil value from many optionals.