Swift One-Line If-Else

Start writing short and concise one-liner if-else statements by using the ternary conditional operator.

Did you know that you can replace this simple if-else statement:

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. You just saw how it can be used in the above one-liner. It is all that simple! For your convenience, here is the structure of a ternary operator:

condition ? true_expression : false_expression

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.

Thanks for reading. I hope you find it useful. Feel free to share it for others to find it too.

Watch a Video About This Topic


A short video on how to use ternary operators in Swift


You Might Be Interested

Swift – Upgrade Your Skills with These 8 Tips

Tuple Destructuring in Swift

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

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