The Adjacent Possible

Ternary Conditional Operator

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!

We’re generating a random number here that will either be 0 or 1.

A Bool optional that will allow us to tell our Guest objects whether they’re attending or not.

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.

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!