Swift One-Line If-Else

A short video on how to use ternary operators in Swift

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

Swift – Upgrade Your Skills with These 8 Tips

Tuple Destructuring in Swift

Leave a Comment

Your email address will not be published. Required fields are marked *