The nil coalescing operator

The nil coalescing operator is similar to the ternary operator that we discussed in Chapter 2, Learning About Variables, Constants, Strings, and Operators. The ternary operator assigns a value to a variable, based on the evaluation of a comparison operator or a Boolean value. The nil coalescing operator attempts to unwrap an optional, and if it contains a value, it will return that value, or a default value if the optional is nil.

Let's look at a prototype for the nil coalescing operator:

optionalA ?? defaultValue 

In this example, we demonstrate the nil coalescing operator when the optional contains a nil and also when it contains a value:

var defaultName = "Jon" 
 
var optionalA: String?  
var optionalB: String? 
 
optionalB = "Buddy" 
 
var nameA = optionalA ?? defaultName  
var nameB = optionalB ?? defaultName 

In this example, we begin by initializing our defaultName variable to Jon. We then define two optionals named optionalA and optionalB. The optionalA variable will be set to nil, while the optionalB variable is set to Buddy.

The nil coalescing operator is used in the final two lines. Since the optionalA variable contains a nil, the nameA variable will be set to the value of the defaultName variable, which is Jon. The nameB variable will be set to the value of the optionalB variable since it contains a value.

The nil coalescing operator is shorthand for using the ternary operator as follows:

var nameC = optionalA != nil ? optionalA! :defaultName 

As we can see, the nil coalescing operator is much cleaner and easier to read than the equivalent ternary operator.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset