Showing posts with label optional binding. Show all posts
Showing posts with label optional binding. Show all posts

Wednesday, August 24, 2016

Not funny, but efficient: Nil coalescing operators

For as funny as the "Who's on first?" skit is, it would all be over in a few seconds if they just exchanged lineup cards rather than falling for a series of counter-intuitive homonyms. Again, lineup cards are not funny, but they are efficient.

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

Friday, August 12, 2016

Optional binding, the late inning defensive replacement of Swift programming

In the last post, we introduced the idea of optionals and how optionals help developers to keep their programs running in case there is no data where there should be data.

Optional binding is like a late inning defensive replacement. You hope you don't need him because he's by no means your best hitter, but you're glad he's there in case your first baseman, middle infielder, third baseman, or catcher catches a case of the yips, just fouled a ball of his leg and can't walk, or just dove into the stands and left half his face in the third row.



Normally, you don't need the defensive replacement, but sometimes you want to make sure nothing funny happens. Normally, the data you need is there and you don't need optional binding, but sometimes there's a chance that it won't be there and that you'll need it.

For example, if you forget to log how you did in your baseball game today, optionals would help deal with that lack of information and keep your baseball performance app tracker from crashing. Here's an example where all the data you need to calculate slugging percentage is there:



As you can see, there is a ? after the abs Double data type. The ? is there because I thought there was a chance a user could forget to include their number of at bats (the same could be said for the other stats) and I wanted to make sure that that variable, abs, was an optional.

In this case, abs has a value and that value is 100. Because there is a value the function runs. But what happens if there is no value? That's where our utility infielder comes to the rescue. Let's take a look:



What would happen if we wrote the same function, but forgot to make the abs variable an optional? This is what that would look like:



What happened? We got an error and our program crashed. And this is why optional binding is helpful. It provides a safety net instead of the program just falling apart and crashing.

And now that we've gone through these three different possible outcomes, let's take a closer look at that, "if let tempAbs = abs" line. What the hell is that? In baseball terms, that is exactly when the manager calls on the defensive replacement (tempAbs) and tells him to go for the starter (abs) because he's afraid the starter is going to drop the data ball. In coding terms, that is when we bind the optional (abs) to a temporary constant to avoid that dropping of the ball to make us call the game altogether (ie, crash the program).

In comes the bench player, tempAbs, out goes the starter, abs. As the manager, you now feel better about your defense and as a programmer, with optional binding you can feel better about your program not crashing.

Challenge: Calculate OPS and make one of the data inputs (hits, at bats, walks, etc) an optional then tweet me your code (@randallmardus). 

On Deck: Optional chaining

Bonus for Faubert: After Jeter left that game, Alex Rodriguez filled in for him at short. Who filled in for Rodriguez at third?