https://www.hackingwithswift.com/example-code/language/what-is-the-nil-coalescing-operator
Because name is an optional string, we need to unwrap it safely to ensure it has a meaningful value.
There are many ways to wrap it, for example, Optional Binding:
1 2 3 |
if let validName = name { // use validName here } |
or guard:
1 2 3 4 5 |
guard let validX = x where x > 0 else { // Value requirements not met, do something return } // do something with ValidX |
nil coalescing operator
Swift’s nil coalescing operator helps you solve this problem by either unwrapping an optional if it has a value, or providing a default if the optional is empty.
1 2 |
let name: String? = nil let unwrappedName = name ?? "Anonymous" |
The nil coalescing operator – ?? – does exactly that, but if it finds the optional has no value then it uses a default instead. In this case, the default is “Anonymous”. What this means is that unwrappedName has the data type String rather than String? because it can be guaranteed to have a value.
You don’t need to create a separate variable to use nil coalescing. For example, this works fine too:
1 2 |
let name: String? = nil print("Hello, \(name ?? "Anonymous")!") |