One-Line If-Else 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.

The Full Syntax

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.

How to Use It?

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 earlier example in this post is a perfect way to use it. It’s 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.

A simple if else can be converted to a one-liner. But don't do it if it makes the code harder to read.

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.

Scroll to Top