Swift Conditionals: ternary conditional

By

Learn how to use the ternary conditional operator in Swift, a shorter version of an if statement that returns one value when true and another when false.

~~~

This tutorial belongs to the Swift series

The ternary conditional operator is a shorter version of an if expression. It evaluates a condition and gives back one value when the condition is true, and another value when it’s false.

Here is the syntax:

`condition` ? `value if true` : `value if false`

Example:

let num1 = 1
let num2 = 2

let smallerNumber = num1 < num2 ? num1 : num2 

// smallerNumber == 1

Read it like a question: is num1 smaller than num2? If yes, give me num1, otherwise give me num2.

When is it useful?

The ternary operator shines when you pick between two values while assigning a constant. The same logic with an if statement takes several lines:

let smallerNumber: Int
if num1 < num2 {
  smallerNumber = num1
} else {
  smallerNumber = num2
}

A more realistic example, calculating a shipping cost that’s free above a threshold:

let total = 120.0
let shipping = total > 100 ? 0.0 : 9.99

// shipping == 0.0

It also works nicely inside string interpolation, where a full if statement wouldn’t fit:

let students = 1
let label = "\(students) student\(students == 1 ? "" : "s")"

// "1 student"

The parts must line up

The condition must be a Bool. Swift won’t accept a number where a boolean is expected, so something like total ? 0.0 : 9.99 does not compile. Write the comparison explicitly.

The two values should also have a compatible type, because the whole expression produces a single value of one type. 0.0 and 9.99 are both Double, so the example above works.

Also note that only the branch that gets picked is evaluated. If the condition is true, Swift never touches the second value. You can rely on this when one branch is a function call you don’t want to run.

Don’t nest ternaries

You can put a ternary inside another ternary, and it compiles:

let temperature = 24
let advice = temperature > 28
  ? "stay inside"
  : temperature > 18 ? "perfect day" : "bring a jacket"

But it’s hard to read, and it gets worse with every level. When you have more than one condition, use an if/else if chain or a switch instead.

My advice: use the ternary for one condition and two values, nothing more. That’s where the shorter syntax makes the code clearer instead of denser.

Tagged: Swift · All topics
~~~

Related posts about swift: