The Ternary Operator in Swift

Let’s group different values into one. What can possibly go wrong?

Steven Curtis
2 min readJan 6, 2020

The ternary operator takes three arguments and returns a result depending on the result of the first expression of the three.

Similar functionality can be derived through using an if-then-else pattern. This is similar, but some would say much clearer.

Let us take a look and see if the use of this operator suits your coding style!

Photo by Tony Hand on Unsplash

Difficulty: Beginner | Easy | Normal | Challenging

Prerequisites:

  • Be able to produce a “Hello, World!” iOS application (guide HERE)

Terminology

Ternary: An operator that takes three arguments. The first argument is a comparison argument, the second the result upon a true comparison of the first argument and the third the result upon a false comparison of the first argument.

Ternary is three

Ternary relies on three different parts of it’s expression to create a result.

The operator uses the : and ? symbols to separate out different parts of the operator.

--

--