Did you know that you can replace this simple if-else
statement in Swift:
let money = 100 if money > 0 { print("Some money") } else { print("No money") }
With this neat one-liner expression?
money > 0 ? print("Some money") : print("No money")
This is possible thanks to what is called a ternary conditional operator in Swift.
For your convenience, here is the structure of a ternary operator:
condition ? true_expression : false_expression
Where:
- condition is an expression that evaluates to true or false.
- true_expression is the piece of code that gets executed if the condition is true.
- false_expression is a piece of code that gets executed if the condition evaluates false.
A ternary conditional operator offers a shorthand that is a useful way to replace simple if-else
statements.
However, itโs not wise to make the code less readable by overusing the one-liner if-else.
Thus, you should only use it for really simple if-else statements.
The above example is a perfect example of a simple enough if-else statement that can be turned into a one-liner. After reducing the expression, the code is still readable yet way shorter.

By the way, it is not wrong to never use one-liner if-else statements in your code.
I have even heard some developers convert these expressions back to the original if-else statements whenever they encounter them in the codebase.
Thanks for reading. I hope you find it useful. Feel free to share it for others to find it too.
You Might Be Interested
About the Author
- I'm an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
Recent Posts
Artificial Intelligence2023.03.14Best AI Tools of 2023 (Save Time & Boost Productivity)
Python2023.02.16How to Pass a Variable from HTML Page to Another (w/ JavaScript)
JavaScript2023.02.16JavaScript How to Get Selected Text from a Textbox
JavaScript2023.02.15JavaScript Select All Text in Div with a Mouse Click