The ternary conditional operator

Now I want to introduce a new operator, one you didn’t see in Chapter 3. It’s called the ternary conditional operator and it’s related to if statements.

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

}

By now you know how this works, but it’s a lot of code. Wouldn’t it be nice if you could shrink this to just a couple of lines? Well, you can, thanks to the ternary conditional operator!

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:

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

You can use this operator to rewrite your long code block above, like so:

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 the value of a; if it’s false, the result will be the value of b.

I’m sure you agree that’s much simpler! This is a useful operator that you’ll find yourself using regularly.

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. If you were paying attention earlier in the book, then you’ll recall you’ve already seen these.

results matching ""

    No results matching ""