In the post on optional chaining, I alluded to how developers prefer to write as little code as necessary. Why write more when less will do? In talking about optional chaining, we also talked about what happens when there is no underlying value to our optional and how to handle that - in that case, by returning nil.
But what if we wanted to return something more helpful or accurate than nil? We can do that. And to do that we use nil coalescing operators. Yes, another programming term that on the surface makes little sense or does little to tell us what it actually does. We'll get to that. For now, let's take a look at nil coalescing operators.
In the last example we laid out a scenario where we bring in our defensive substitute, Steven Souza, to play leftfield for Ryan Zimmerman. But in this case, we forgot to make the substition and there's no one out in left! Fortunately, optional binding kicks in and while our value for leftFielder is nil, the program returns our else statement, "No one is playing leftfield!"

In the example below we still don't have a leftfielder, but we do have a faster way of getting to that result (line 14).

What happened? We got the program to return the same string, "No one is playing leftfield!" two different ways. The first way, through optional binding, took about four lines of code (lines 8-12). The second way, with a nil coalescing operator, all took place on line 14. Not too shabby. Here's what the trimmed down version looks like:

Now how do we make sense of that nil coalescing operator moniker? Here's how I explain it to myself: coalesce means to come together to form one group or mass. Here the ?? operator is bringing together the nil value of the empty optional (the stuff to the left of the ??) with the outcome based on what should happen when that optional value is nil (the stuff to the right of the ??) to form a single respone which, in this case, is "No one is playing leftfield!"
We can even take the nil coalescing operator a step further and work in some optional chaining like this:

Pretty slick, right? We can read this as, "If there is a value for leftFielder then capitalize it and return it. If the value for leftFielder is nil, then return, 'No one is playing leftfield!'"
Challenge: Take the example you wrote in the optional chaining post and re-write it using optional chaining then tweet it at me (@randallmardus).
On Deck: Force unwrapping optionals
No comments:
Post a Comment