Swift - nil-coalescing operator

Introduction

Swift has a nil-coalescing operator to supply a default value when a nil is encountered.

For example, you are looking for a particular value in a dictionary, and if it doesn't exist you instead provide a default value.

You can make this shorter using the nil-coalescing operator:

Demo

var values = ["name":"fred"] 
var personsAge = "unspecified" 

personsAge = values["age"] ?? "unspecified" 
print("They are \(personsAge) years old")

Result

Swift dictionaries support the concept of a default value.

So, the following code works exactly the same as the preceding version:

Demo

var values = ["name":"fred"] 
var personsAge = "unspecified" 


personsAge = values["age", default: "unspecified"] 
print("They are \(personsAge) years old")

Result

Related Topic