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. The syntax is:

(<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 min example, the condition is a < b. If that is true, min is a; otherwise it is b.

min and max in the standard library do the same job.

Feedback about page:

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



Table Of Contents