Ternary operator

suggest change

Conditions may also be evaluated in a single line using the ternary operator:

If you wanted to determine the minimum and maximum of two variables, you could use if statements, like so:

let a = 5
let b = 10
let min: Int

if a < b {
    min = a 
} else {
    min = b 
}

let max: Int

if a > b {
    max = a 
} else {
    max = b 
}

The ternary conditional operator takes a condition and returns one of two values, depending on whether the condition was true or false. The syntax is as follows: This is equivalent of having the expression:

(<CONDITION>) ? <TRUE VALUE> : <FALSE VALUE>

The above code can be rewritten using ternary conditional operator as below:

let a = 5
let b = 10
let min = a < b ? a : b
let max = a > b ? a : b

In the first example, the condition is a < b. If this is true, the result assigned back to min will be of a; if it’s false, the result will be the value of b.

Note: Because finding the greater or smaller of two numbers is such a common operation, the Swift standard library provides two functions for this purpose: max and min.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents