Overview
The ternary conditional operator is a compact way to choose between two values. It checks a Boolean condition, then returns one value when the condition is true and another value when the condition is false.
It is most useful when the decision is simple and the result is an expression, such as choosing a label, a color, a number, or a small piece of view state.
Basic Syntax
The ternary operator has three parts: the condition, the value for true, and the value for false.
condition ? valueIfTrue : valueIfFalseYou can read it as: if this condition is true, use the first value; otherwise, use the second value.
Simple Example
Here is a basic ternary expression that chooses a message based on a score.
let score = 86
let result = score >= 60 ? "Passed" : "Try again"
print(result)Because score >= 60 is true, result becomes "Passed".
Ternary vs If-Else
A ternary expression is often a shorter version of a simple if-else assignment.
let isLoggedIn = true
let buttonTitle: String
if isLoggedIn {
buttonTitle = "Log Out"
} else {
buttonTitle = "Log In"
}
let compactButtonTitle = isLoggedIn ? "Log Out" : "Log In"Both values contain the same result. The ternary version is shorter because it directly returns one of two strings.
Using Ternary with Numbers
The two possible results do not have to be strings. You can return numbers, booleans, optionals, enum cases, or any other compatible type.
let itemCount = 3
let shippingCost = itemCount > 0 ? 4.99 : 0.0
print(shippingCost)This kind of one-line value selection can keep simple calculations readable.
Using Ternary with Booleans
A ternary expression can also return a Boolean, although you should avoid using it when the condition already gives you the Boolean you need.
let age = 21
let canEnter = age >= 18 ? true : false
let simplerCanEnter = age >= 18The second version is clearer because the comparison already returns true or false.
Using Ternary with Optionals
Ternary expressions are handy when you want to choose a fallback display value for an optional.
let username: String? = nil
let displayName = username == nil ? "Guest" : username!
print(displayName)This works, but optional binding or nil coalescing is usually cleaner for this specific case.
let username: String? = nil
let displayName = username ?? "Guest"
print(displayName)Using Ternary in SwiftUI
SwiftUI code often uses ternary expressions for small visual differences, such as choosing text, colors, or system images.
import SwiftUI
struct StatusBadge: View {
let isComplete: Bool
var body: some View {
Text(isComplete ? "Done" : "Open")
.foregroundStyle(isComplete ? .green : .orange)
}
}This works well because each ternary expression stays short and the visual intent is still easy to scan.
Using Ternary with Enums
You can return enum cases from a ternary expression as long as Swift can infer the type.
enum DownloadState {
case waiting
case active
}
let hasNetwork = true
let state: DownloadState = hasNetwork ? .active : .waitingAdding the type annotation to state helps Swift know which enum the shorthand cases belong to.
When Ternary Gets Too Busy
Ternary expressions are best for small choices. If each branch needs multiple lines, side effects, or nested conditions, use if-else or switch instead.
let temperature = 31
let message = temperature > 30 ? "Hot" : "Comfortable"That example is easy to read. This one is harder to maintain:
let score = 92
let grade = score >= 90 ? "A" : score >= 80 ? "B" : "C"Nested ternaries can work, but they are easy to misread. A switch or if-else chain is often better for that kind of logic.
Common Mistakes
Using ternary for complex logic
If the expression takes effort to understand, expand it into a regular control flow statement.
Forgetting that both branches need compatible types
Swift needs the true and false results to produce one clear type.
let value = isEnabled ? "On" : "Off"Using ternary when nil coalescing is clearer
For optional fallback values, ?? is often the better fit.
Quick Reference
| Syntax | What It Does |
|---|---|
condition ? a : b | Returns a when the condition is true, otherwise returns b |
isLoggedIn ? "Log Out" : "Log In" | Chooses between two strings |
count > 0 ? 4.99 : 0.0 | Chooses between two numbers |
isComplete ? .green : .orange | Chooses between two SwiftUI styles |
optional ?? fallback | Often clearer than ternary for optional fallbacks |
if-else | Better for multi-line or complex logic |
Summary
- The ternary operator chooses between two values.
- Its format is
condition ? valueIfTrue : valueIfFalse. - Use it for simple expressions and short assignments.
- The two possible results should have compatible types.
- Use
if-elseorswitchwhen the logic becomes complex. - Use nil coalescing when you only need an optional fallback.
The ternary operator is not meant to replace every if-else. It shines when the decision is small, the two outcomes are obvious, and the code reads naturally on one line.