6.8 The Ternary Operator
Swift supports the ternary operator to provide a shortcut way of making decisions within code. The syntax of the ternary operator (also known as the conditional operator) is as follows:
condition ? true expression : false expression
The way the ternary operator works is that condition is replaced with an expression that will return either true or false. If the result is true then the expression that replaces the true expression is evaluated. Conversely, if the result was false then the false expression is evaluated. Let’s see this in action:
let x = 10
let y = 20
print("Largest number is \(x > y ? x : y)")
The above code example will evaluate whether x is greater than y. Clearly this will evaluate to false resulting in y being returned to the print call for display to the user:
Largest number is 20