How to Use Swift's Ternary Conditional Operator

How to Use Swift's Ternary Conditional Operator

At the time of writing, Swift defines a single ternary operator, the ternary conditional operator. As the name suggest, a ternary operator operates on three operands. An operand can be a value or an expression.

How Does It Work?

Take a look at this example. I recommend firing up Xcode and creating a playground to follow along. Writing code is the best way to learn.

let numberOfLegs = 4

// Ternary Conditional Operator
let animal = numberOfLegs > 2 ? "mammal" : "bird"

We define a constant, numberOfLegs, and assign the value 4 to it. We define another constant, animal, and assign the result of an expression to it. The expression uses Swift's ternary conditional operator to infer whether the animal is a mammal or a bird.

The idea is simple. The expression before the question mark (?) is evaluated. If the expression evaluates to true, the value or expression before the colon (:) is returned. If the expression evaluates to false, the value or expression after the colon (:) is returned. In this example, the value of animal is mammal because the value stored in numberOfLegs is greater than 2.

An Alternative to Swift's If-Else Statement

We can replace the ternary conditional operator with an if-else statement. The main difference is the number of lines.

let numberOfLegs = 4

let animal: String

// If-Else Statement
if numberOfLegs > 2 {
    animal = "mammal"
} else {
    animal = "bird"
}

Not only is the first snippet, using the ternary conditional operator, more concise, it is easier to read. Does that mean you should always use ternary conditional operator over Swift's if-else statement? Absolutely not. You should always choose readability over brevity. Don't try to be clever if that compromises the readability of your code.

Always choose readability over brevity.