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
conditionis true,expression1is executed. - if
conditionis false,expression2is executed.
The ternary operator takes 3 operands (condition, expression1, and expression2). Hence, the name ternary operator.
Example: Swift Ternary Operator
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
with
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,
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.