The ternary operator is a conditional operator that you can use to write complex conditions using just one line of code. It is straightforward to use and powerful.
In this article, I will highlight the most common use cases of the ternary operator in Swift. I will also review the advantages and disadvantages of writing conditions using the ternary operator instead of if-else statements.
- This article is part of the Learn Swift series.
FREE GUIDE - SwiftUI App Architecture: Design Patterns and Best Practices
MVC, MVVM, and MV in SwiftUI, plus practical lessons on code encapsulation and data flow.
DOWNLOAD THE FREE GUIDETable of contents
- Writing conditions using only one line of code
- Assign values to constants and variables based on certain conditions
- Calling functions based on certain conditions
- Writing nested conditions in a single statement using multiple ternary operators
Writing conditions using only one line of code
The ternary operator is a shorthand for if-else statements.
Let’s take, for example, a simple calculator app with two basic operations: addition and subtraction.
let operation = "add"
let first = 10
let second = 10
if operation == "add" {
print("The sum of \(first) and \(second) is \(first + second).")
} else {
print("The difference between \(first) and \(second) is \(first - second).")
}
The above logic can be rewritten using just one line of code with the ternary operator.
let operation = "add"
let first = 10
let second = 10
operation == "add"
? print("The sum of \(first) and \(second) is \(first + second).")
: print("The difference between \(first) and \(second) is \(first - second).")
The ternary operator works with three things: a condition and two statements. The statement executed if the condition is true
is placed after the question mark. The statement executed if the condition is false
is placed after the colon.
You may think the ternary operator is just syntactic sugar for simple if…else statements. But it is so much more. Let’s look at some advantages of using the ternary operator in your code.
Assign values to constants and variables based on certain conditions
Let’s say the calculator app also determines the minimum and maximum values of two given whole numbers.
let first = 10
let second = 10
let min: Int
let max: Int
if first < second { min = first } else { min = second } if first > second {
max = first
} else {
max = second
}
min
and max
are assigned values twice in the above if-else statements. You can simplify this logic with a ternary operator.
let first = 10
let second = 10
let min = first < second ? first : second let max = first > second ? first : second
The ternary operator sets both min
and max
to either first
or second
. min
and max
are now only assigned values once.
You can combine the previous if-else statements into a single statement.
let first = 10
let second = 10
let min: Int
let max: Int
if first < second {
min = first
max = second
} else {
min = second
max = first
}
However, min
and max
are assigned values twice. You may think that you can simplify things with the ternary operator.
let first = 10
let second = 10
let min: Int
let max: Int
first < second ? min = first max = second : min = second max = first
However, the code crashes because you cannot have multiple instructions after either the question mark or the colon of the ternary operator.
The previous if-else statement can be rewritten with a tuple instead.
let first = 10
let second = 10
let (min, max): (Int, Int)
if first < second {
(min, max) = (first, second)
} else {
(min, max) = (second, first)
}
The (min, max)
tuple is assigned values twice. The ternary operator works as expected.
let first = 10
let second = 10
let (min, max) = first < second ? (first, second) : (second, first)
The tuple stores the minimum and maximum values of the whole numbers as before and is assigned a value once.
Calling functions based on certain conditions
Now let’s imagine that the calculator app also determines if a particular whole number is either even or odd.
let number = 10
if number % 2 == 0 {
print("\(number) is an even number.")
} else {
print("\(number) is an odd number.")
}
There are two print
function calls in the code. This logic can be simplified using ternary operators.
let number = 10
print(number % 2 == 0
? "\(number) is an even number."
: "\(number) is an odd number.")
The code now uses the remainder operator to check the whole number’s parity. The entire logic is encapsulated inside one print
function call.
You have only converted simple if-else statements to ternary operator statements so far. Next, we’ll look at how to convert nested if-else statements to multiple ternary operator statements.
Writing nested conditions in a single statement using multiple ternary operators
You can use a nested if-else statement to determine the full name of a specific person from their first and last names.
let firstName = "Cosmin"
let lastName = "Pupăză"
let name: String
if firstName != "" {
if lastName != "" {
name = firstName + " " + lastName
} else {
name = firstName
}
} else {
if lastName != "" {
name = lastName
} else {
name = ""
}
}
The code covers all of the possible cases. The values of the constants of the first and last names can be empty strings or not. The name
constant is therefore assigned values four times.
You can simplify this logic with multiple ternary operators.
let firstName = "Cosmin"
let lastName = "Pupăză"
let name = firstName != ""
? lastName != ""
? firstName + " " + lastName
: lastName
: lastName != ""
? lastName
: ""
The name
constant is assigned a value once. The assignment is indented on multiple lines, making it easy to read and understand.
Conclusion
In this article, I have highlighted the most common use cases of the ternary operator in Swift. The most important thing to remember is that you can always revert to equivalent if-else statements if and only if the ternary operator statements don’t work as expected in your code.
SwiftUI App Architecture: Design Patterns and Best Practices
It's easy to make an app by throwing some code together. But without best practices and robust architecture, you soon end up with unmanageable spaghetti code. In this guide I'll show you how to properly structure SwiftUI apps.
Cosmin has been writing tutorials and books on Swift and iOS development since 2014, when the first version of Swift was released. He has been part of influential iOS development communities such as raywenderlich.com and appcoda.com since 2010 and has taught iOS development with Objective-C and Swift since 2012. Cosmin lives in Romania and has engineering degrees in electronics, telecommunications, neural networks, microprocessors, microcontrollers, distributed systems, and web technologies from the technical universities of Cluj-Napoca and Iași. He has worked with many programming languages over the years, but none of them has had such a significant impact on himself as Swift. Cosmin likes to play the guitar or study WW2 history when not coding