Operators

Operators

Operators are at the core of any programming language. Common examples of operators are + and , AND, OR, || just to name a few. We will be updating this page with further examples as time goes on.

Ternary Operator

Today we are discussing the ternary conditional operator and how it is used in the Swift language. If you’ve never heard of a ternary operator, don’t feel bad — it’s a tiny part of Swift that’s easy to overlook.

The ternary operator is used to shorten the classic if/else statement. In our example, we have a Boolean called shouldSave, and depending on if it is true or not, we call one of two methods saveNow() or cancelNow().

The if/else statement


if shouldSave {
   saveNow()
}else{
   cancelNow()
}

You may be thinking, that code is pretty short, how could it get any simpler? Enter the ternary operator and one that may just top your list of future code snippets.

shouldSave ? saveNow() : cancelNow()

Ternary operators are useful in many cases but should be used with caution as they have the ability to confuse the readability of your code. Used properly they can be a quick way to handle simple situations where you would normally use the if/else statement.