Swift Ternary Operator Tutorial

by Dimitris Tasios
21 views

In this article, we will learn how to use the ternary operator in Swift.

1. What Is a Ternary Operator in Swift?

A ternary operator in Swift is an alternative way to write a simple, relatively small if-else statement. The syntax of the ternary operator is the following:

a_condition ? statement_if_condition_is_true : statement_if_condition_is_false

That syntax would be equivalent to the following if-else syntax:

if a_condition {
    statement_if_condition_is_true
} else {
    statement_if_condition_is_false
}

2. Ternary Operator Example

Let’s see a simple example to understand how a ternary operator can help make our code clearer. In the following example, we have a function that prints the number we provide as its parameter. If the number is greater than 10, we do not print its actual value, but stick with 10.

// only numbers less than 10 are allowed
func max10(number: Int) {
    let resultNumber = number < 10 ? number : 10
    print("Your number: \(number). Final number: \(resultNumber).")
}

max10(number: 3)
max10(number: -9)
max10(number: 20)

The output is:

Your number: 3. Final number: 3.
Your number: -9. Final number: -9.
Your number: 20. Final number: 10.

The aforementioned function is the equivalent of the following function, written with an if-else statement instead:

func max10IfElse(number: Int) {
    var resultNumber: Int
    if number < 10 {
        resultNumber = number
    } else {
        resultNumber = 10
    }
    print("Your number: \(number). Final number: \(resultNumber).")
}

max10IfElse(number: 3)
max10IfElse(number: -9)
max10IfElse(number: 20)

The output is:

Your number: 3. Final number: 3.
Your number: -9. Final number: -9.
Your number: 20. Final number: 10.

As you can see, the output is the same between the two functions. However, the former function is much clearer and shorter than the latter, since the if-else statement of the second function that required 6 lines, while the ternary operator of the first function was written in one line.

3. Nested Ternary Operator

Like in if-else statements, a ternary operator in Swift can nest another ternary operator. In fact, we can nest as many ternary operators as we wish. Let’s see an example of a nested ternary operator.

In this example, we want to check whether a number is within 3 and 7. Depending on whether it is or not, we print an appropriate message.

let number = 5
let messageNumberIsBetween3And7 = number >= 3 ? (number <= 7 ? "\(number) is between 3 and 7." : "\(number) is not between 3 and 7.") : "\(number) is not between 3 and 7."
print(messageNumberIsBetween3And7)

The output is:

5 is between 3 and 7.

As you can see thought, the ternary operator quickly became too cluttered and complex, with a simple nested ternary operator. As a result, it’s not recommended to use nested ternary operators. Take a look at the equivalent if-else statement:

if number >= 3 {
    if number <= 7 {
        print("\(number) is between 3 and 7.")
    } else {
        print("\(number) is not between 3 and 7.")
    }
} else {
    print("\(number) is not between 3 and 7.")
}

In that case, it’s much more clear what the flow of our logic is.

4. Limitation of Ternary Operators

In all of our examples, you might have noticed that all alternative paths of a ternary operator do a similar thing compared to the rest of the paths. For instance, in our max10 example, all paths returned an integer. Or, in our previous example, all paths returned a string.

Even though it’s not necessary for the ternary operator to return a value (for example, it could simply print a message), the limitation of the ternary operator is that it cannot have diverse alternative paths; they all have to agree to either provide a value of one type or all of them to not provide any value at all.

For instance, the following if-else statement cannot be written with a ternary operator:

var aNumber = 10
if aNumber == 10 {
    print(aNumber)
} else {
    aNumber = 0
}

If we try to write that with a ternary operator, we would get a compile error:

let invalid = (aNumber == 10 ? print(aNumber) : 0) // INVALID: Result values in '? :' expression have mismatching types '()' and 'Int'
(aNumber == 10 ? print(aNumber) : 0)               // INVALID: same error as above

The reason for that is that one path of the ternary operator prints a value and, thus, doesn’t return anything, while the other path returns an integer.

For the sake of completeness, the following two ternary operators are valid:

aNumber == 10 ? print(aNumber) : print(0)          // VALID: it isn't saved in a variable since it doesnt return anything
let alsoValid = (aNumber == 10 ? aNumber : 0)      // VALID: each path returns an integer, which is saved on our constant "alsoValid"

In those two operators, both paths do a similar thing; the ones on the first operator both print something, while the ones on the second both return something of the same type.

5. Conclusion

By now, you should be able to use the ternary operator in Swift. You can find the source code (Playground) on our GitHub page.

Related Posts