Ternary operator in Swift explained
Published on: July 7, 2025The ternary operator is one of those things that will exist in virtually any modern programming language. When writing code, a common goal is to make sure that your code is succinct and no more verbose than it needs to be. A ternary expression is a useful tool to achieve this.
What is a ternary?
Ternaries are essentially a quick way to write an if statement on a single line. For example, if you want to tint a SwiftUI button based on a specific condition, your code might look a bit as follows:
struct SampleView: View {
@State var username = ""
var body: some View {
Button {} label: {
Text("Submit")
}.tint(username.isEmpty ? .gray : .red)
}
}
The line where I tint the button contains a ternary and it looks like this: username.isEmpty ? .gray : .red
. Generally speaking, a ternary always has the following shape <condition> ? <if true> : <else>
. You must always provide all three of these "parts" when using a ternary. It's basically a shorthand way to write an if {} else {}
statement.
When should you use ternaries?
Ternary expressions are incredibly useful when you're trying to assign a property based on a simple check. In this case, a simple check to see if a value is empty. When you start nesting ternaries, or you find that you're having to evaluate a complex or long expression it's probably a good sign that you should not use a ternary.
It's pretty common to use ternaries in SwiftUI view modifiers because they make conditional application or styling fairly straightforward.
That said, a ternary isn't always easy to read so sometimes it makes sense to avoid them.
Replacing ternaries with if expressions
When you're using a ternary to assign a value to a property in Swift, you might want to consider using an if / else expression
instead. For example:
let buttonColor: Color = if username.isEmpty { .gray } else { .red }
This syntax is more verbose but it's arguably easier to read. Especially when you make use of multiple lines:
let buttonColor: Color = if username.isEmpty {
.gray
} else {
.red
}
For now you're only allowed to have a single expression on each codepath which makes them only marginally better than ternaries for readability. You also can't use if expressions everywhere so sometimes a ternary just is more flexible.
I find that if expressions strike a balance between evaluating longer and more complex expressions in a readable way while also having some of the conveniences that a ternary has.