How often do developers utilize ternary operators

How often do you use ternary operators rather than conditionals in writing clean code?


let firstCard = 10

let secondCard = 11

print(firstCared > secondCard ? "Card has higher value" : "Card has lesser value")

This is a general programming question than a Swift question, so this isn't really the best forum to get useful answers. However, this is just a question of style. Some communities of programmers really like ternary operators, and some communities really dislike them, and some communities don't care. So in practice whether or not you will use them basically depends on who you're programming with (and for).

If you like that style, use it. If you don't, don't. Anything you can write with the ternary operator can also be expressed via if/else/etc.

A fun footnote: in languages that don't have static typing, you sometimes see people use short-circuiting operators instead of ternaries. For example in Python you can write:

"Card has " + ("higher" if firstCard > secondCard else "lower or equal") + " value"

but you can also write:

"Card has " + (firstCard > secondCard and "higher" or "lower or equal") + " value"

Python programmers, in general, don't much like this style, but you see it in some other similar languages (also, it only works correctly if the first result is truthy, so you can't use it all the time).


I use them for assignment whenever possible.

let x = condition
  ? true_value
  : false_value

reads better than

let x: Type
if condition { x = true_value } else { x = false_value }

"Tenary is ugly" & maybe slow to compile
Would be nice if we have if/else expression

1 Like

With a slight rearrangement, this also chains nicely when “switching” over separate conditions:

let x = a ? p
      : b ? q
      : c ? r
      : d ? s
      :     t
Terms of Service

Privacy Policy

Cookie Policy