The Ternary Operator in Swift

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

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!

Image for post
Image for post
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.

Image for post
Image for post

Imagine we take a user input

Imagine we want to tell anyone whose name is not Steve to Go away. We can create an If statement for this.

var name = "Steve"
if name == Steve {
print ("Welcome")
} else {
print ("Go away!")
}

It’s a few lines. Not bad.
Now what about the Ternary operator?

var name = "Steve"
name == Steve ? print ("Welcome") : print ("Go away!")

Which, I’m sure you’ll agree is shorter!

You can read the Ternary code as

“If the name is Steve, print Welcome otherwise print Go away!”

Conclusion

If you are coming from any language that has theseC-like Ternary Operators you will already be familiar with their flexibility and the fact that their use can help you to write easy to understand code.

The brevity of code matters, and if you are writing code that is functional in nature the use of this operator will make your code easier to read.

As ever, happy coding!

Want to get in contact? Try the link here:

https://twitter.com/stevenpcurtis

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store