Member-only story
5 Useful Swift One-Liners To Write Concise Code
Learn a bunch of one-liners to improve code readability
1. One-Liner If-Else Operator
Did you know that you can replace this simple if-else
statement:
With this neat little one-liner expression?
money > 0 ? print("Some money") : print("No money")
This is actually known as a ternary conditional operator in Swift (it’s a common feature in other programming languages too).
Here is the general structure of a ternary conditional:
condition ? true_expression : false_expression
Be mindful when using this, though. This shorthand is a useful way to replace simple if-else
statements. However, it’s not wise to make the code less readable by overusing it.
2. Swap Two Variables Without a Helper
In order to swap two variables without a helper variable, you can utilize tuple destructuring: