Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Nil-Coalescing Operator in Swift
Written by Team Kodeco

The nil-coalescing operator unwraps an optional and returns the value if it exists or a default value if the optional is nil. The operator is composed of two question marks ?? and is used between an optional and a default value.

This operator is particularly useful when working with optional values that you expect to have a default value. For example, when working with user input, you might expect a user to provide a name, but if they don’t, you can use a default value, such as “Anonymous”.

let name: String? = nil
let defaultName = "Anonymous"
let unwrappedName = name ?? defaultName
print(unwrappedName) // prints "Anonymous"

In this example, name is an optional String that is set to nil, the default name is set to “Anonymous”, and unwrappedName is the result of the name ?? defaultName operation. Since name is nil, unwrappedName is set to the value of “Anonymous”.

© 2024 Kodeco Inc.