UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to use the ternary conditional operator for quick tests

Paul Hudson    @twostraws   

Updated for Xcode 15

There’s one last way to check conditions in Swift, and when you’ll see it chances are you’ll wonder when it’s useful. To be fair, for a long time I very rarely used this approach, but as you’ll see later it’s really important with SwiftUI.

This option is called the ternary conditional operator. To understand why it has that name, you first need to know that +, -, ==, and so on are all called binary operators because they work with two pieces of input: 2 + 5, for example, works with 2 and 5.

Ternary operators work with three pieces of input, and in fact because the ternary conditional operator is the only ternary operator in Swift, you’ll often hear it called just “the ternary operator.”

Anyway, enough about names: what does this actually do? Well, the ternary operator lets us check a condition and return one of two values: something if the condition is true, and something if it’s false.

For example, we could create a constant called age that stores someone’s age, then create a second constant called canVote that will store whether that person is able to vote or not:

let age = 18
let canVote = age >= 18 ? "Yes" : "No"

When that code runs, canVote will be set to “Yes” because age is set to 18.

As you can see, the ternary operator is split into three parts: a check (age >= 18), something for when the condition is true (“Yes”), and something for when the condition is false (“No”). That makes it exactly like a regular if and else block, in the same order.

If it helps, Scott Michaud suggested a helpful mnemonic: WTF. It stands for “what, true, false”, and matches the order of our code:

  • What is our condition? Well, it’s age >= 18.
  • What to do when the condition is true? Send back “Yes”, so it can be stored in canVote.
  • And if the condition is false? Send back “No”.

Let’s look at some other examples, start with an easy one that reads an hour in 24-hour format and prints one of two messages:

let hour = 23
print(hour < 12 ? "It's before noon" : "It's after noon")

Notice how that doesn’t assign the result anywhere – either the true or false case just gets printed depending on the value of hour.

Or here’s one that reads the count of an array as part of its condition, then sends back one of two strings:

let names = ["Jayne", "Kaylee", "Mal"]   
let crewCount = names.isEmpty ? "No one" : "\(names.count) people"
print(crewCount)

It gets a little hard to read when your condition use == to check for equality, as you can see here:

enum Theme {
    case light, dark
}

let theme = Theme.dark

let background = theme == .dark ? "black" : "white"
print(background)

The = theme == part is usually the bit folks find hard to read, but remember to break it down:

  • What? theme == .dark
  • True: “black”
  • False: “white”

So if theme is equal to .dark return “Black”, otherwise return “White”, then assign that to background.

Now, you might be wondering why the ternary operator is useful, particularly when we have regular if/else conditions available to us. I realize it’s not a great answer, but you’ll have to trust me on this: there are some times, particularly with SwiftUI, when we have no choice and must use a ternary.

You can see roughly what the problem is with our code to check hours:

let hour = 23
print(hour < 12 ? "It's before noon" : "It's after noon")

If we wanted to write that out using if and else we’d either need to write this invalid code:

print(
    if hour < 12 {
        "It's before noon"
    } else {
        "It's after noon"
    }
)

Or run print() twice, like this:

if hour < 12 {
    print("It's before noon")
} else {
    print("It's after noon")
}

That second one works fine here, but it becomes almost impossible in SwiftUI as you’ll see much later. So, even though you might look at the ternary operator and wonder why you’d ever use it, please trust me: it matters!

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.8/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.