In programming, it's quite common to write code in the following form
if (statement evaluating to true or false) { assign or return a value } else { assign or return a different value }For example we might write this inside a function:
if x == y {
return 7
} else {
return 42
}
The ternary operator allows us to simplify this into a single line in the following format:
(statement evaluating to true or false) ? (value for true) : (value for false)We could therefore write this inside a function instead of the above example inside a function:
return x == y ? 7 : 42
The ternary operator also helps with other problems. If we want to assign a variable to one of two values depending on some evaluation, we either have to assign it to one value, then change it if required, e.g. as follows:
var x = 3
if (y == z) {
x = 4
}
or use an optional, e.g.: var x : Int!
if (y == z) {
x = 4
} else {
x = 3
}
Furthermore if we wanted to assign a let
constant to one of two values, depending on the result of evaluating an expression, we would have to store the value in a variable first (or give up using a constant)
With the ternary operator, all these issues go away, e.g.
let x = y == z ? 4 : 3
For readability, it may help to put the boolean expression in parentheses, e.g. let x = (y == z) ? 4 : 3