Using the Nil Coalescing Operator (??)

Swift is designed to be a “safe” language, which means it provides commands to help you write code that minimizes the risk of crashes. Of course, Swift is only as safe as the programmer, but Swift at least provides tools to minimize crashes, unlike C which provides multiple ways for programmers to shoot themselves in the foot.

One way crashes occur is when a variable gets a value of nil and can’t handle it. So the program crashes. That’s why Swift offers something called the nil coalescing operator, which looks like two question marks (??).

The nil coalescing operator lets you assign a variable to an optional variable. If the optional variable is nil, then the nil coalescing operator assigns the variable a default value.

var str: String? = "Value here"

let myString = str ?? "Safe value here"

print (myString)

In this example, we create an optional variable called “str” and assign it the string “Value here”.

The second line tries to assign this optional variable to the “myString” variable. The nil coalescing operator tells Swift, “If the ‘str’ value is not nil, then assign it to myString. Otherwise assign the value ‘Safe value here’ to myString instead.”

The above code stores “Value here” in the myString variable. Let’s give str a nil value like this:

var str: String? = nil

let myString = str ?? "Safe value here"

print (myString)

Because str is nil, myString now contains the value “Safe value here”.

As a general rule, if a variable can be optional, then make sure your code can work whether the optional variable is nil or not. This just makes your code safer and less likely to crash.

 

August 6th, 2018 by
HTML Snippets Powered By : XYZScripts.com