Ternary Operator

Ternary Operator in Swift is used to return one of the two values based on the evaluation of a condition.

So, basically, Ternary Operator consists of three parts. The first is the condition, then two values, say value1 and value2. And the syntax of Ternary Operator is as shown in the following.

condition ? value1 : value2

If condition evaluates to true, then it returns value1, else if the value is false , then function returns value2.

value1 and/or value2 could be an expression as well, that evaluates to some value.

Example

In the following example, we will evaluate a condition, and return one of the two values, based on the condition, using Ternary Operator.

main.swift

import Foundation

var input = 2
var result = (input == 1 ? 25 : 41)
print("Result : \(result)")

Output

Result : 41

In the ternary operator expression, the condition is input == 1, value1 is 25 and value2 is 41. Since the condition evaluate to false for input value of 2, second value is returned.

Now, let us take a value for input such that the condition evaluates to true.

main.swift

import Foundation

var input = 1
var result = (input == 1 ? 25 : 41)
print("Result : \(result)")

Output

Result : 25

Since the condition in the Ternary Operator is true, the first value is returned.

ADVERTISEMENT

Nested Ternary Operator

Just like if-else statement, Ternary Operator can be nested.

Nesting is placing Ternary Operator inside another Ternary Operator.

In the following example, we have nested a Ternary Operator inside another Ternary Operator.

main.swift

import Foundation

var input1 = 1
var input2 = 5
var result = (input1 == 1 ? (input2 == 5 ? 87 : 99) : 41)
print("Result : \(result)")

Output

Result : 87

Conclusion

In this Swift Tutorial, we learned what Ternary Operator is in Swift programming, and how to use it, with the help of examples.