😀 ? 👍 : 👎
If you code in any way or form, then you must have used if else statements quite a bit or else I would call you a liar. //code ? use if/else : print(liar)
I know that I flood my code with if/else statements to get the logic correct and it is definitely a huge part of coding in general. If you are as big of a stickler for syntax and sleek looks as I am, then you might find ways to shorten code to make it more readable.
With this overly simple example, I used 5 lines of code to preserve the readability of the code.
Or I can do this in two lines and have everyone hate me till the end of time.
Or I can use a ternary operator and write the exact same code on one line.
Now don’t get me wrong, if you haven’t encountered ternaries before, this makes absolutely no bloody sense. But if it does it just seems to flow so so well. I personally love using ternary when the code isn’t overly complicated and can fit on one line.
So lets explain what is happening! Ternary means of three parts, meaning three statements. There are two pieces of syntax to this operator and three statements which will let everything run smoothly. The ternary syntax is a ‘?’ and a ‘:’. Question mark and colon! Thats it.
The first statement must be a comparative one before the question mark. The second statement between the ? and : only gets called if the first statement is TRUE. The third statement after the colon is called if the first statement is FALSE. So in short the ternary is just a short hand for IF/ELSE.
And one last thing, ternaries can be used to assign a value!
let bestNumber = int1 < int2 ? int2 : int1
I’m not gonna lie, I will almost ALWAYS write out if / else first. When I reread my code and find that it can be shortened AND still stay readable, then I will turn it in to ternary. I have many pieces of code that stay as if / else statements because it just makes sense. So don’t go on a crazy reorganization spree to use ternaries in every opportunity possible, though I know you Are tempted.
If you are into these shorthand ways of coding, then by all means join me in my pathetic attempt of trying to look cool while coding. As for now… I’m going to just post random images of code where I use ternary.
This ternary checks if hasSwitched is false which will then set isSorting to false to break out of the while-loop. I’ve recently found a new way to writing that line just a tad shorter while keeping the same functionality.
isSorting = !hasSwitched ? false : true
This ternary only uses the middle statement and the end statement is filled with a Void parenthesis. Could have been better written with an if-statement
A pretty one line recursive function for factorials.
Another ternary with a statement being Void, could have used if-statement just as effectively. Oops.
And this final one isn’t related to anything , I just really like it.
TLDR — Ol’ nessy asking for tree fiddy again.