Programming tips for everyone

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 little 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 orthers 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
Share on twitter
Share on linkedin

Related Articles

Artturi Jalli

Technical Writer

Entrepreneur, Software Engineer, Mobile App Dev, MSc Physics Student, And Tech Enthusiast from Finland


My Personal Favorites

Buy an Online Course

Lorem ipsum dolor sit amet consectetur adipiscing elit dolor
Explore Categories