O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Ternary Operator

The ternary operator is very similar to an if/else statement, but has the more concise syntax 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 in the middle. This particular ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required