Overview
The nil coalescing operator (??) in Swift is a simple yet powerful tool that allows developers to handle optional values with ease. It provides a way to return a default value when an optional is nil. This operator is particularly useful when dealing with optional values that might not always contain data, ensuring your code can fall back on a predefined value rather than crashing or behaving unpredictably.
Code Snippet
var optionalName: String? = nil
let defaultName = "Guest"
let nameToDisplay = optionalName ?? defaultName
print(nameToDisplay) // Output: GuestCode Explanation
-
var optionalName: String? = nil: This line declares an optional string variableoptionalNameand initializes it withnil. The question mark (?) indicates that the variable can hold aStringor benil. -
let defaultName = "Guest": Here, a constantdefaultNameis defined with the value"Guest". This will serve as the fallback value ifoptionalNameisnil. -
let nameToDisplay = optionalName ?? defaultName: This line demonstrates the nil coalescing operator. It checks whetheroptionalNamecontains a value. SinceoptionalNameisnil, the expression returnsdefaultName, which is"Guest". -
print(nameToDisplay): This prints the value ofnameToDisplay, which is"Guest"in this case, sinceoptionalNamewasnil.
The nil coalescing operator is a concise and effective way to handle optional values in Swift. By providing a clear path for fallback values, it helps developers write safer and more predictable code. Whether you’re dealing with user input, data parsing, or optional configurations, the nil coalescing operator ensures your app behaves gracefully when encountering nil.

