A ternary operator can be used to replace the if...else
statement in certain scenarios.
Before you learn about the ternary operator, make sure to know about Swift if...else statement.
Ternary Operator in Swift
A ternary operator evaluates a condition and executes a block of code based on the condition. Its syntax is
condition ? expression1 : expression2
Here, the ternary operator evaluates condition
and
- if
condition
is true,expression1
is executed. - if
condition
is false,expression2
is executed.
The ternary operator takes 3 operands (condition
, expression1
, and expression2
). Hence, the name ternary operator.
Example: Swift Ternary Operator
// program to check pass or fail
let marks = 60
// use of ternary operator
let result = (marks >= 40) ? "pass" : "fail"
print("You " + result + " the exam")
Output
You pass the exam.
In the above example, we have used a ternary operator to check pass or fail.
let result = (marks >= 40) ? "pass" : "fail"
Here, if marks
is greater or equal to 40, pass
is assigned to result
. Otherwise, fail
is assigned to result
.
Ternary operator instead of if...else
The ternary operator can be used to replace certain types of if...else
statements. For example,
You can replace this code
// check the number is positive or negative
let num = 15
var result = ""
if (num > 0) {
result = "Positive Number"
}
else {
result = "Negative Number"
}
print(result)
with
// ternary operator to check the number is positive or negative
let num = 15
let result = (num > 0) ? "Positive Number" : "Negative Number"
print(result)
Output
Positive Number
Here, both programs give the same output. However, the use of the ternary operator makes our code more readable and clean.
Nested Ternary Operators
We can use one ternary operator inside another ternary operator. This is called a nested ternary operator in Swift. For example,
// program to check if a number is positive, zero, or negative
let num = 7
let result = (num == 0) ? "Zero" : ((num > 0) ? "Positive" : "Negative")
print("The number is \(result).")
Output
The number is Positive.
In the above example, we the nested ternary operator ((num > 0) ? "Positive" : "Negative"
is executed if the condition num == 0
is false
.
Note: It is recommended not to use nested ternary operators as they make our code more complex.