Ternary Operator

The ternary operator is very similar to an if/else statement, but has more concise syntax. The syntax looks likes this: a ? b : c. In English, the ternary operator reads something like, “If a is true, then do b. Otherwise, do c.”

Let’s rewrite the town population check that used if/else using the ternary operator instead.

Listing 3.3  Using the ternary operator

...
if population < 10000 {
    message = "\(population) is a small town!"
} else {
    message = "\(population) is pretty big!"
}

message = population < 10000 ? "\(population) is a small town!" :
                     "\(population) is pretty big!"
...

The ternary operator can be a source of controversy: some programmers love it; some programmers loathe it. We come down somewhere ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.