Use Ternary Conditional Operator in Swift
Written by Team Kodeco
The ternary conditional operator is a shorthand way of writing a common type of if-else
statement.
The general syntax for the ternary operator is:
condition ? valueIfTrue : valueIfFalse
Here’s an example of using the ternary conditional operator to write a common type of if-else
statement:
let a = 5
let b = 2
let max = a > b ? a : b // 5
In this example, the variable a
is set to 5 and variable b
is set to 2. The ternary conditional operator is used to determine which variable is greater and assigns the greater value to the variable max
.
Note that the ternary operator is much more concise than the corresponding if statement:
let max: Int
if (a > b) {
max = a
} else {
max = b
}
However, some people find the longer form more readable. Use your best judgment to determine the tradeoffs between conciseness and readability.