Swift Ternary Operator: condition ? a : b, Type Rules and if Expressions

The Swift ternary operator condition ? a : b checks a Bool condition and gives back a when it is true and b when it is false. It is an expression, so it fits anywhere a value fits: a let, a function argument, a return or a string interpolation, and only the chosen side is evaluated. Both sides must produce one type, the condition must be a real Bool, and the ? needs a space on both sides. The rest of this article covers how Swift types the two branches, why precedence catches people out, how the ternary compares with the if expressions added in Swift 5.9, and when ??, if or switch is the better tool.

Difficulty: Beginner

Helpful to know first: how an if/else statement works, comparison operators such as >= that produce a Bool, and declaring constants with let.

How condition ? a : b Chooses a Value

Read condition ? a : b as a question: "Is the condition true? Then a. Otherwise b." It is called ternary because it takes three operands, and it is the only operator in Swift that does. The Swift documentation calls it the ternary conditional operator.

Swift
let temperature = 31
let advice = temperature > 25 ? "Bring water" : "Bring a jacket"
print(advice)
// Output: Bring water
Output✓ Tested · Swift 6.4
Bring water

The same decision written as an if statement needs a constant declared first and assigned in each block:

Swift
let temperature = 31
let advice: String
if temperature > 25 {
    advice = "Bring water"
} else {
    advice = "Bring a jacket"
}
print(advice)
// Output: Bring water
Output✓ Tested · Swift 6.4
Bring water

The difference is more than length. The if statement runs one of two blocks of code. The ternary is a single expression that produces a value, which is why it can sit inside other expressions, and an if statement cannot. The Swift if-else article covers the statement form.

Only the chosen branch runs

Swift evaluates the condition first, then exactly one of the two branches.

Swift
func loadFromCache() -> String {
    print("reading cache")
    return "cached data"
}

func loadFromNetwork() -> String {
    print("calling server")
    return "fresh data"
}

let isOffline = true
let data = isOffline ? loadFromCache() : loadFromNetwork()
print(data)
// Output:
// reading cache
// cached data
Output✓ Tested · Swift 6.4
reading cache
cached data

loadFromNetwork() never runs, so it is safe to put an expensive call, or one that only works in some states, in a branch. It runs only when it is chosen.

Three rules the compiler enforces

  • The condition must be a Bool. Swift has no "truthy" values: an Int, a String or an optional is not a condition.
  • Both branches must produce one common type. The next sections show how Swift finds it.
  • The ? and the : need whitespace on both sides. Without the space, flag? is read as optional chaining.

Ternary Examples From Everyday Swift Code

Choosing a word inside string interpolation

Plural labels are the classic use. The ternary goes straight inside \( ), and string literals inside the interpolation are fine.

Swift
for count in [1, 3] {
    print("You have \(count) \(count == 1 ? "message" : "messages")")
}
// Output:
// You have 1 message
// You have 3 messages
Output✓ Tested · Swift 6.4
You have 1 message
You have 3 messages

An if statement cannot appear here at all, because interpolation needs a value. If the interpolation grows hard to read, move the ternary into its own constant first. More on the syntax in Swift string interpolation.

Returning a value from a computed property

A computed property or function whose body is a single expression returns it without the return keyword, and a ternary is a single expression.

Swift
struct Product {
    let name: String
    let stock: Int

    var availability: String {
        stock > 0 ? "\(stock) in stock" : "Sold out"
    }
}

let lamp = Product(name: "Lamp", stock: 0)
let desk = Product(name: "Desk", stock: 4)
print(lamp.availability, "|", desk.availability)
// Output: Sold out | 4 in stock
Output✓ Tested · Swift 6.4
Sold out | 4 in stock

This keeps short display logic next to the data it describes, without a four-line if.

Picking a number for a calculation

The condition can be any Bool expression, including one built with || and &&.

Swift
let subtotal = 42.5
let isMember = true
let shipping = subtotal >= 50 || isMember ? 0.0 : 4.99
print("Shipping: \(shipping)")
// Output: Shipping: 0.0
Output✓ Tested · Swift 6.4
Shipping: 0.0

No parentheses are needed around the condition: || binds more tightly than ? :, so Swift reads (subtotal >= 50 || isMember) ? 0.0 : 4.99. The Swift logical operators article explains || and &&.

Choosing an enum case or a closure

The branches can be any kind of value, including enum cases and closures, as long as Swift knows the type.

Swift
enum Theme { case light, dark }

let hour = 22
let theme: Theme = hour >= 20 || hour < 7 ? .dark : .light

let shout = true
let format: (String) -> String = shout ? { $0.uppercased() } : { $0.lowercased() }

print(theme, format("Swift"))
// Output: dark SWIFT
Output✓ Tested · Swift 6.4
dark SWIFT

Both annotations are required. .dark is shorthand for Theme.dark, and without : Theme Swift reports cannot infer contextual base in reference to member 'dark'. The closures need (String) -> String for the same reason: without it, the error is cannot infer type of closure parameter '$0' without a type annotation.

How Swift Decides the Type of a Ternary Expression

A whole ? : expression has one type, and the compiler must know it at compile time, before anyone knows which branch will run. It solves both branches together, along with any annotation, as one problem. That is why literals in the two branches can adapt to each other. The general mechanism is explained in Swift type inference.

Branches Result type Why
flag ? 1 : 2.5 Double The literal 1 can become a Double; 2.5 cannot become an Int
flag ? "Rex" : nil String? nil makes the whole result optional
flag ? Dog() : Cat() Animal The closest common superclass of the two classes
An Int constant and a Double constant Error Values whose types are already fixed are never converted
flag ? .dark : .light with no annotation Error Nothing says which type .dark belongs to
Swift
class Animal {
    var name: String { "animal" }
}
class Dog: Animal {
    override var name: String { "dog" }
}
class Cat: Animal {
    override var name: String { "cat" }
}

let wantsDog = false
let pet = wantsDog ? Dog() : Cat()
let score = wantsDog ? 1 : 2.5
let nickname = wantsDog ? "Rex" : nil
print(pet.name, score, nickname ?? "none")
// Output: cat 2.5 none
Output✓ Tested · Swift 6.4
cat 2.5 none

pet is declared as an Animal (Option-click it in Xcode to see), holding a Cat. score is a Double whichever branch runs: 2.5 here, or 1.0 if wantsDog were true, never the Int 1. nickname is a String?, so it needs unwrapping before use.

Ternary Precedence: Why Parentheses Change the Answer

The ternary operator has lower precedence than every other operator except assignment (=, += and friends). Swift therefore groups everything on the left, including arithmetic, comparisons, &&, || and ??, into the condition before it looks at the ?. The false branch is just as greedy: everything after the : up to the end of the expression belongs to it. The full table is in Swift operator precedence.

That works in your favour for conditions, as in the shipping example above. It works against you when the ternary is only one part of a bigger calculation, so wrap it in parentheses there:

Swift
let basePrice = 40
let isMember = true
let price = basePrice + (isMember ? 0 : 5)
print(price)
// Output: 40
Output✓ Tested · Swift 6.4
40

Without the parentheses, Swift reads (basePrice + isMember) ? 0 : 5, which does not compile. The mistakes section below shows the exact errors.

Chaining ternaries for more than two outcomes

The ternary operator is right-associative, so a ? x : b ? y : z means a ? x : (b ? y : z). A chain therefore reads like if / else if / else:

Swift
let score = 72
let grade = score >= 90 ? "A"
          : score >= 80 ? "B"
          : score >= 70 ? "C"
          : "F"
print(grade)
// Output: C
Output✓ Tested · Swift 6.4
C

Swift accepts this, and one line per outcome keeps it readable. Past two conditions, an if expression or a switch with ranges is easier to read and to extend.

Ternary Operator vs if Expressions in Swift 5.9 and Later

Since Swift 5.9, if and switch can be used as expressions: let x = if condition { a } else { b }. That covers much of what the ternary does, but the rules differ.

Ternary ? : if expression
Outcomes Two (chain for more) Any number, with else if
Unwrap optionals No Yes, with if let
Where it can appear Anywhere a value fits: arguments, interpolation, inside other expressions Only as the value of a let/var, an assignment, a return (including an implicit one) or a throw
Branch types Solved together: flag ? 1 : 2.5 is a Double Each branch checked alone: if flag { 1 } else { 2.5 } is an error without an annotation
nil in one branch Gives an optional Needs a type annotation
Content of a branch One expression One expression (or a throw)
Swift
let score = 85
let note: String? = "Great work"

let grade = if score >= 90 { "A" } else if score >= 80 { "B" } else { "C" }
let message = if let note { note } else { "No comment" }
let badge = score >= 80 ? "Honors" : "Standard"

print(grade, message, badge)
// Output: B Great work Honors
Output✓ Tested · Swift 6.4
B Great work Honors

The if expression handles the three-way grade and the optional unwrap, which the ternary cannot do cleanly. The ternary stays the shortest form for the two-way badge. The if form has its own errors: print(if flag { 1 } else { 2 }) fails with 'if' may only be used as expression in return, throw, or as the source of an assignment, a missing else gives 'if' must have an unconditional 'else' to be used as expression, and let x = if flag { 1 } else { 2.5 } gives branches have mismatching types 'Int' and 'Double'.

A practical rule: use the ternary for a short two-way choice, especially inside a larger expression. Use an if expression when you need else if, unwrapping, or branches long enough to wrap. Use switch for many cases (see Swift switch statements).

Predict the Output

Both snippets test the type of a ternary expression, not which branch runs.

Snippet 1: two numeric branches

Swift
let isWholeNumber = true
let value = isWholeNumber ? 10 : 2.5
print(value)
print(isWholeNumber ? 10 : 25)

What does this print?

Show answer

It prints 10.0 and then 10.

The type of value is decided from both branches at compile time. 2.5 can only be a floating-point number, so the literal 10 becomes a Double as well, and value is 10.0 even though the true branch looks like an integer. On the last line both branches are integer literals, so the result is the Int 10.

Snippet 2: an optional branch

Swift
let nickname: String? = nil
let shown = nickname != nil ? nickname : "Guest"
print(shown)

What does this print?

Show answer

It prints Optional("Guest"), and the compiler warns expression implicitly coerced from 'String?' to 'Any'.

Checking nickname != nil does not unwrap it. The true branch is still a String?, so the literal "Guest" becomes a String? too, and shown is optional. Printing an optional shows the Optional(…) wrapper. The fix is not a ternary at all: let shown = nickname ?? "Guest" is a plain String.

Common Ternary Operator Mistakes and Their Errors

Writing the question mark without a space before it

In Swift, a ? attached to the end of a name means optional chaining, so the space before the ternary ? is required.

Problem: isMember? is read as optional chaining on a Bool. Swift reports consecutive statements on a line must be separated by ';' and cannot use optional chaining on non-optional value of type 'Bool'.

Swift
let isMember = true
let label = isMember? "Member" : "Guest"
Compiler output✓ Tested · Swift 6.4
error: consecutive statements on a line must be separated by ';'

Fix: Put whitespace on both sides of ? and :.

Swift
let isMember = true
let label = isMember ? "Member" : "Guest"
print(label)
// Output: Member
Output✓ Tested · Swift 6.4
Member

The corrected version works because a ? with spaces on both sides can only be the ternary operator.

Using a number or an optional as the condition

Code ported from C, JavaScript or Python often treats 0 and empty values as false.

Problem: Swift does not convert values to Bool. An Int condition fails with type 'Int' cannot be used as a boolean; test for '!= 0' instead, and an optional one with optional type 'String?' cannot be used as a boolean; test for '!= nil' instead.

Swift
let unread = 3
let couponCode: String? = "SAVE10"
let badge = unread ? "New mail" : "No mail"
let banner = couponCode ? "Coupon applied" : "No coupon"
Compiler output✓ Tested · Swift 6.4
error: type 'Int' cannot be used as a boolean; test for '!= 0' instead

Fix: Write the comparison you mean, as the error messages suggest.

Swift
let unread = 3
let couponCode: String? = "SAVE10"
let badge = unread != 0 ? "New mail" : "No mail"
let banner = couponCode != nil ? "Coupon applied" : "No coupon"
print(badge, "|", banner)
// Output: New mail | Coupon applied
Output✓ Tested · Swift 6.4
New mail | Coupon applied

The corrected version works because != produces a real Bool, which is the only thing a condition accepts.

Leaving out parentheses when the ternary is part of a calculation

A ternary in the middle of arithmetic or string concatenation almost always needs parentheses.

Problem: Because + binds more tightly, Swift reads (basePrice + isMember) ? 0 : 5 and reports cannot convert value of type 'Bool' to expected argument type 'Int' and type 'Int' cannot be used as a boolean; test for '!= 0' instead.

Swift
let basePrice = 40
let isMember = true
let price = basePrice + isMember ? 0 : 5
Compiler output✓ Tested · Swift 6.4
error: cannot convert value of type 'Bool' to expected argument type 'Int'

Fix: Wrap the whole ternary in parentheses so it is evaluated first.

Swift
let basePrice = 40
let isMember = true
let price = basePrice + (isMember ? 0 : 5)
print(price)
// Output: 40
Output✓ Tested · Swift 6.4
40

The corrected version works because the parentheses make the ternary one operand of +.

Returning values whose types are already different

Literals adapt to each other, but constants and variables already have a fixed type.

Problem: flatFee is an Int and percentFee is a Double, so Swift reports result values in '? :' expression have mismatching types 'Int' and 'Double'.

Swift
let flatFee = 2
let percentFee = 1.75
let useFlatFee = false
let fee = useFlatFee ? flatFee : percentFee
Compiler output✓ Tested · Swift 6.4
error: result values in '? :' expression have mismatching types 'Int' and 'Double'

Fix: Convert one branch so both produce the same type.

Swift
let flatFee = 2
let percentFee = 1.75
let useFlatFee = false
let fee = useFlatFee ? Double(flatFee) : percentFee
print(fee)
// Output: 1.75
Output✓ Tested · Swift 6.4
1.75

The corrected version works because both branches are now Double, so the ternary has one type.

Find the Bug

A shop charges 5 for shipping, free above 50, and every order also pays a packing fee of 2. This code compiles and runs, but a 60 order is charged 0 instead of 2. Find the bug.

Swift
let subtotal = 60
let packingFee = 2
let extraCharge = subtotal > 50 ? 0 : 5 + packingFee
print("Extra charge: \(extraCharge)")
// Output: Extra charge: 0
Show answer

The false branch takes everything after the colon. Swift reads the line as subtotal > 50 ? 0 : (5 + packingFee), so the packing fee is added only when shipping is not free. Free-shipping orders skip it.

Parenthesise the ternary so the packing fee is added in both cases:

Swift
let subtotal = 60
let packingFee = 2
let extraCharge = (subtotal > 50 ? 0 : 5) + packingFee
print("Extra charge: \(extraCharge)")
// Output: Extra charge: 2
Output✓ Tested · Swift 6.4
Extra charge: 2

Splitting it into let shipping = subtotal > 50 ? 0 : 5 and then shipping + packingFee works too, and is easier to read.

When to Use the Ternary Operator and When Not To

The ternary is the right tool for a short choice between two values. For other jobs, Swift has something clearer.

Situation Better choice
Two short values chosen by one condition The ternary operator
A default for an optional name ?? "Guest", not name != nil ? name! : "Guest"
The condition already is the answer age >= 18, not age >= 18 ? true : false
Three or more outcomes An if expression or switch
Unwrapping an optional while choosing if let, as a statement or an expression
Running code for its effect: printing, saving, assigning An if statement
Swift
let nickname: String? = nil
let age = 20

let shown = nickname ?? "Guest"
let isAdult = age >= 18
print(shown, isAdult)
// Output: Guest true
Output✓ Tested · Swift 6.4
Guest true

?? both checks and unwraps, so shown is a plain String; see the Swift nil-coalescing operator. A comparison already produces a Bool, so wrapping it in ? true : false adds nothing.

For side effects, isOn ? print("on") : print("off") does compile, because both branches are Void, but it hides control flow inside an expression. Assignments inside the branches do not even compile: flag ? count = 1 : count = 2 fails with cannot assign to value: result of conditional operator '? :' is never mutable. Write count = flag ? 1 : 2, or an if statement. The ternary is not a performance tool either, so choose it for readability only (see readability over cleverness).

Swift Ternary Operator Interview Questions

Can you overload the ternary operator or define your own?

No. ? : is built into the language, not a function, and the Swift documentation states that it cannot be overloaded. Custom operators in Swift can only be prefix, infix or postfix, so you cannot declare another three-operand operator either.

What is the difference between ? : and ??

a ?? b unwraps an optional a, or uses b when a is nil. The ternary chooses between two values based on any Bool. Swift has no shorthand "Elvis" form a ?: b; ?? is the Swift equivalent.

What is the type of flag ? 1 : 2.5, and of if flag { 1 } else { 2.5 }?

The ternary is a Double, because both branches are solved together and the literal 1 can become a Double. The if expression does not compile without an annotation, because each branch is checked on its own and 1 settles on Int.

Try It Yourself

  • Write a function batteryStatus(level:isCharging:minutesLeft:) that returns a String.
  • Use a ternary to choose "charging" or "on battery".
  • Add " - low" only when the level is below 20 and the device is not charging.
  • Use a ternary to write "1 minute" but "40 minutes".
  • Call it for a level of 15 not charging with 1 minute left, 15 charging with 40 minutes, and 80 not charging with 300 minutes.

Expected output, one line per call: 15% on battery - low, 1 minute left, 15% charging, 40 minutes left and 80% on battery, 300 minutes left.

Hint: && binds more tightly than ? :, so the low-battery condition needs no parentheses. Build each part as its own constant, then combine them in one interpolated string.

Show solution
Swift
func batteryStatus(level: Int, isCharging: Bool, minutesLeft: Int) -> String {
    let source = isCharging ? "charging" : "on battery"
    let warning = level < 20 && !isCharging ? " - low" : ""
    let unit = minutesLeft == 1 ? "minute" : "minutes"
    return "\(level)% \(source)\(warning), \(minutesLeft) \(unit) left"
}

print(batteryStatus(level: 15, isCharging: false, minutesLeft: 1))
print(batteryStatus(level: 15, isCharging: true, minutesLeft: 40))
print(batteryStatus(level: 80, isCharging: false, minutesLeft: 300))
// Output:
// 15% on battery - low, 1 minute left
// 15% charging, 40 minutes left
// 80% on battery, 300 minutes left
Output✓ Tested · Swift 6.4
15% on battery - low, 1 minute left
15% charging, 40 minutes left
80% on battery, 300 minutes left

Summary

  • condition ? a : b is an expression: it produces a or b, evaluates only the chosen side, and fits anywhere a value fits.
  • The condition must be a real Bool, and ? and : need spaces on both sides.
  • Both branches are typed together: literals adapt (flag ? 1 : 2.5 is a Double), nil makes the result optional, and fixed types that differ are an error.
  • The ternary has the lowest precedence except assignment and is right-associative: parenthesise it inside calculations, and remember the false branch takes everything after the colon.
  • Since Swift 5.9, an if expression is clearer for else if chains and if let; use ?? for optional defaults and an if statement for side effects.

A good next step is the nil-coalescing operator, the right tool whenever the choice is really "this optional, or a default".