Home > Articles > Programming > General Programming/Other Languages

  • Print
  • + Share This
This chapter is from the book

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 in the middle. This particular usage is not very elegant. Your assignment to message requires more than a simple a ? b : c. The ternary operator is great for concise statements, but if your statement starts wrapping to the next line, we think you should use if/else instead.

Hit Command-Z to undo, removing the ternary operator and restoring your if/else statement.

Listing 3.4 Restoring if/else

...
message = population < 10000 ? "\(population) is a small town!" :
                     "\(population) is pretty big!"
if population < 10000 {
    message = "\(population) is a small town!"
} else {
    message = "\(population) is pretty big!"
}
...
  • + Share This
  • 🔖 Save To Your Account