December 2015
Intermediate to advanced
400 pages
13h 3m
English
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 ...
Read now
Unlock full access