Ternary Conditional Operator

May 7, 2016

Getting rid of if-else statements is what the ternary operator was made for. Once you learn about it you'll be tempted to refactor all your code. But where would you look to refactor? I'm gonna take you through a quick example of what that looks like.

Here's a bit of ugly code that could be improved A LOT!

  1. We're generating a random number here that will either be 0 or 1.
  2. A Bool optional that will allow us to tell our Guest objects whether they're attending or not.
  3. Depending on the random number we set attending to 'true' or 'false.
  4. Create a new guest with a nil value for isAttending.
  5. Verify attending isn't nil and then change the guest isAttending to it's proper value.
  6. Append our guest to the array.
  7. Create a new array variable that will contain all attending guest.
  8. Iterate through the guests array and if the guest is attending we append it to our attendingGuest array.

There's a lot we could improve but I want to look at part 3. In part 3 we have one question with an answer of 'true' or false'. Apples own definition of what a ternary operator is as follows:

"The ternary conditional operator is a special operator with three parts, which takes the form question ? answer1 : answer2. It is a shortcut for evaluating one of two expressions based on whether question is true or false."

We'll refactor that single piece of code and then compare the two.

At first glance you can see it's much shorter. Sometimes that means not as readable but in this case it's much easier to see what's going on. Second, attending is now a constant since I won't be mutating it later and it's not an optional so there's 0% chance of it being nil.

I'll break down what's happening in that line section by section.

Question: "Is random equal to the int 1" (random == 1)

Answer 1: If question is true set attending equal to 'true' (? true : false)

Answer 2: if question is false set attending equal to 'false' (? true : false)

There you have it. Maybe a little confusing as first but I hope you can now apply it to the code you write. I did go on to refactor some more of that code to be even shorter and take advantage of more Swifty features.

That's the final product. If you have any questions or improvements of your own tell me about them! I'm eager to here about how others are improving their code so I can improve mine too! Thanks and I hope you'll share/like/email/post or anything else to spread the word, I'd be extremely grateful!