# Swift Ternary Operator

Source: https://devdocs10.com/articles/swift/swift-ternary-operator  
By Murat Bo · Updated 2026-10-17 · DevDocs10 (https://devdocs10.com)

In Swift, the ternary operator is a compact way to choose between two values based on a condition. It is useful when you want to assign one value if something is `true` and another value if something is `false`.

The ternary operator is also called the **conditional operator** because it uses a condition to decide which value should be used. It is commonly used for simple assignments, short messages, UI labels, computed properties, and small decisions inside Swift code.

At first, the ternary operator can look strange because it uses symbols instead of words. However, once you understand its three parts, it becomes easy to read and useful in everyday Swift programming.

> Tip: Use the ternary operator for simple value choices. If the logic becomes long or difficult to read, use an `if` statement instead.

## What Is the Ternary Operator in Swift?

The ternary operator lets you choose between two possible values using this structure:

```swift
condition ? valueIfTrue : valueIfFalse
```

You can read it like this:

1. Check the condition.
2. If the condition is `true`, use the value after the question mark.
3. If the condition is `false`, use the value after the colon.

The word **ternary** means that the operator works with three parts:

- The condition
- The value used when the condition is true
- The value used when the condition is false

## Basic Ternary Operator Example

Before using the ternary operator, look at a normal `if` and `else` statement.

#### Using if else

```swift
let age = 20
let message: String

if age >= 18 {
    message = "You are an adult"
} else {
    message = "You are a minor"
}

print(message)
// Output: You are an adult
```

Output (tested with Swift 6.4):

```text
You are an adult
```

This code checks whether `age` is greater than or equal to `18`. If the condition is true, the message says the person is an adult. Otherwise, the message says the person is a minor.

#### Using the ternary operator

```swift
let age = 20

let message = age >= 18 ? "You are an adult" : "You are a minor"

print(message)
// Output: You are an adult
```

Output (tested with Swift 6.4):

```text
You are an adult
```

Both examples do the same thing. The ternary version is shorter because it is only choosing between two values.

## Ternary Operator Syntax

The Swift ternary operator follows this syntax:

```swift
let result = condition ? trueValue : falseValue
```

The condition must produce a Boolean value. A Boolean value is either `true` or `false`.

#### Example

```swift
let score = 75

let status = score >= 60 ? "Passed" : "Failed"

print(status)
// Output: Passed
```

Output (tested with Swift 6.4):

```text
Passed
```

Here, `score >= 60` is true, so Swift chooses `"Passed"`.

## Understanding the Three Parts

### 1. The Condition

The condition is the part that Swift checks first. It must evaluate to either `true` or `false`.

```swift
let temperature = 30

let weather = temperature > 25 ? "Hot" : "Cool"

print(weather)
// Output: Hot
```

Output (tested with Swift 6.4):

```text
Hot
```

The condition `temperature > 25` is true, so the result is `"Hot"`.

### 2. The True Value

The true value is used when the condition evaluates to `true`.

```swift
let isLoggedIn = true

let buttonTitle = isLoggedIn ? "Logout" : "Login"

print(buttonTitle)
// Output: Logout
```

Output (tested with Swift 6.4):

```text
Logout
```

### 3. The False Value

The false value is used when the condition evaluates to `false`.

```swift
let hasDiscount = false

let priceLabel = hasDiscount ? "Discount applied" : "No discount"

print(priceLabel)
// Output: No discount
```

Output (tested with Swift 6.4):

```text
No discount
```

## Why Use the Ternary Operator?

The ternary operator is useful when an `if else` statement feels too long for a simple decision.

#### Longer approach

```swift
let points = 90
let grade: String

if points >= 50 {
    grade = "Pass"
} else {
    grade = "Fail"
}

print(grade)
// Output: Pass
```

Output (tested with Swift 6.4):

```text
Pass
```

#### Shorter approach

```swift
let points = 90

let grade = points >= 50 ? "Pass" : "Fail"

print(grade)
// Output: Pass
```

Output (tested with Swift 6.4):

```text
Pass
```

The shorter version is easier to scan because the logic is simple. It asks one question and chooses one of two values.

## The Ternary Operator Is an Expression

In Swift, the ternary operator is an expression. An expression is code that produces a value.

This means you can use the ternary operator anywhere Swift expects a value.

### 1. Assigning a Value

```swift
let stock = 12

let availability = stock > 0 ? "In stock" : "Out of stock"

print(availability)
// Output: In stock
```

Output (tested with Swift 6.4):

```text
In stock
```

### 2. Passing a Value to a Function

```swift
let unreadMessages = 5

print(unreadMessages > 0 ? "You have unread messages" : "No new messages")
// Output: You have unread messages
```

Output (tested with Swift 6.4):

```text
You have unread messages
```

### 3. Returning a Value from a Function

```swift
func accessMessage(isMember: Bool) -> String {
    return isMember ? "Welcome, member!" : "Please sign up"
}

print(accessMessage(isMember: true))
print(accessMessage(isMember: false))

// Output:
// Welcome, member!
// Please sign up
```

Output (tested with Swift 6.4):

```text
Welcome, member!
Please sign up
```

## Type Rules in the Ternary Operator

Swift is a type-safe language. This means Swift checks that values are used in a consistent way. With the ternary operator, the true and false results should usually be compatible types.

### Correct: Both Results Are Strings

```swift
let isPremiumUser = true

let accountType = isPremiumUser ? "Premium" : "Free"

print(accountType)
// Output: Premium
```

Output (tested with Swift 6.4):

```text
Premium
```

Both possible results are strings, so Swift understands that `accountType` is a `String`.

### Correct: Both Results Are Numbers

```swift
let isExpressShipping = false

let shippingDays = isExpressShipping ? 1 : 5

print(shippingDays)
// Output: 5
```

Output (tested with Swift 6.4):

```text
5
```

Both possible results are integers, so Swift treats `shippingDays` as an `Int`.

### Common Mistake: Mixing Unclear Result Types

```swift
let isAvailable = true

// Avoid unclear result types.
let value = isAvailable ? "Available" : 0
```

This code does not compile: one result is a `String` and the other is an `Int`, and Swift cannot infer a single type for the whole expression from them. Keep both results as the same kind of value.

```swift
let isAvailable = true

let value = isAvailable ? "Available" : "Unavailable"

print(value)
// Output: Available
```

Output (tested with Swift 6.4):

```text
Available
```

> Tip: When using the ternary operator, ask: “What one type should this expression produce?” If the answer is unclear, use an `if` statement.

## Using the Ternary Operator with Strings

A common use of the ternary operator is choosing text for the user.

```swift
let itemCount = 1

let itemText = itemCount == 1 ? "item" : "items"

print("You have \(itemCount) \(itemText).")
// Output: You have 1 item.
```

Output (tested with Swift 6.4):

```text
You have 1 item.
```

This is useful when a label changes based on a count.

## Using the Ternary Operator with Numbers

You can use the ternary operator to choose between numeric values.

```swift
let orderTotal = 250

let discount = orderTotal >= 200 ? 25 : 0

print("Discount: $\(discount)")
// Output: Discount: $25
```

Output (tested with Swift 6.4):

```text
Discount: $25
```

## Using the Ternary Operator with Boolean Values

Sometimes beginners use the ternary operator to return `true` or `false`. This often works, but it is usually unnecessary.

#### Unnecessary ternary

```swift
let age = 22

let canVote = age >= 18 ? true : false

print(canVote)
// Output: true
```

Output (tested with Swift 6.4):

```text
true
```

#### Better version

```swift
let age = 22

let canVote = age >= 18

print(canVote)
// Output: true
```

Output (tested with Swift 6.4):

```text
true
```

The condition already returns a Boolean value, so the ternary operator is not needed.

## Using the Ternary Operator in String Interpolation

String interpolation means placing values inside a string using `\(...)`. You can use the ternary operator inside string interpolation when one part of a message changes.

```swift
let username = "Maya"
let isOnline = true

let message = "\(username) is \(isOnline ? "online" : "offline")."

print(message)
// Output: Maya is online.
```

Output (tested with Swift 6.4):

```text
Maya is online.
```

This is helpful for short messages. If the expression becomes hard to read, create a separate variable first.

```swift
let username = "Maya"
let isOnline = true

let statusText = isOnline ? "online" : "offline"
let message = "\(username) is \(statusText)."

print(message)
// Output: Maya is online.
```

Output (tested with Swift 6.4):

```text
Maya is online.
```

## Using the Ternary Operator with Optionals

An optional in Swift is a value that may contain something or may contain `nil`. The value `nil` means there is no value.

You can use the ternary operator to handle optionals, but it is not always the best choice.

```swift
let nickname: String? = nil

let displayName = nickname != nil ? nickname! : "Guest"

print(displayName)
// Output: Guest
```

Output (tested with Swift 6.4):

```text
Guest
```

This works, but it uses force unwrapping with `!`. Force unwrapping can crash your program if the optional is unexpectedly `nil`.

### Better Option: Nil-Coalescing Operator

For optional default values, Swift usually has a better tool: the nil-coalescing operator `??`.

```swift
let nickname: String? = nil

let displayName = nickname ?? "Guest"

print(displayName)
// Output: Guest
```

Output (tested with Swift 6.4):

```text
Guest
```

Use the ternary operator for general true-or-false choices. Use `??` when you only need a default value for an optional.

## Using the Ternary Operator in SwiftUI

In SwiftUI, the ternary operator is often used to choose simple view values such as text, colors, or labels based on state.

```swift
import SwiftUI

struct StatusView: View {
    let isActive: Bool

    var body: some View {
        Text(isActive ? "Active" : "Inactive")
    }
}
```

This view displays `"Active"` when `isActive` is true and `"Inactive"` when it is false.

#### SwiftUI color example

```swift
import SwiftUI

struct BadgeView: View {
    let isPremium: Bool

    var body: some View {
        Text(isPremium ? "Premium" : "Free")
            .padding()
            .background(isPremium ? Color.yellow : Color.gray)
    }
}
```

This pattern is useful when a view changes slightly based on a simple state value.

## Nested Ternary Operators

A nested ternary operator means placing one ternary operator inside another. This can choose from more than two values, but it can also become difficult to read.

```swift
let score = 85

let grade = score >= 90 ? "A" :
            score >= 80 ? "B" :
            score >= 70 ? "C" :
            "Needs improvement"

print(grade)
// Output: B
```

Output (tested with Swift 6.4):

```text
B
```

This works, but beginners should be careful. Nested ternary expressions can become harder to understand than regular `if`, `else if`, and `else` statements.

#### More readable version

```swift
let score = 85
let grade: String

if score >= 90 {
    grade = "A"
} else if score >= 80 {
    grade = "B"
} else if score >= 70 {
    grade = "C"
} else {
    grade = "Needs improvement"
}

print(grade)
// Output: B
```

Output (tested with Swift 6.4):

```text
B
```

> Tip: Nested ternary operators are valid Swift, but they are not always good Swift. Use them only when the result is still easy to read.

## Ternary Operator vs if else

The ternary operator and `if else` statements both help you make decisions. The main difference is how they are best used.

| Feature | Ternary Operator | if else Statement |
| --- | --- | --- |
| Main purpose | Choose between two values | Run different blocks of code |
| Best for | Short, simple decisions | Longer or multi-step logic |
| Readability | Clear when simple, confusing when nested | Usually clearer for complex logic |
| Returns a value | Yes | Not directly in traditional statement form |
| Common use | Assigning text, numbers, or UI values | Validation, branching, and multiple actions |

## Common Beginner Misunderstandings

### 1. Thinking the Question Mark Always Means Optional

Swift also uses `?` with optionals, but the ternary operator is different.

```swift
// Optional type
let name: String?

// Ternary operator
let message = isLoggedIn ? "Welcome" : "Please log in"
```

The same symbol can have different meanings depending on where it appears.

### 2. Forgetting the Colon

The ternary operator always needs both the question mark and the colon.

```swift
// Incorrect
let result = isValid ? "Valid"

// Correct
let result = isValid ? "Valid" : "Invalid"
```

### 3. Using It for Too Much Logic

The ternary operator should not hide complex logic in one line.

```swift
// Hard to read
let message = isLoggedIn ? hasSubscription ? "Premium dashboard" : "Upgrade now" : "Please log in"
```

A clearer version is:

```swift
let message: String

if isLoggedIn {
    if hasSubscription {
        message = "Premium dashboard"
    } else {
        message = "Upgrade now"
    }
} else {
    message = "Please log in"
}
```

## Advanced Usage

After you understand the basics, the ternary operator can be useful in more advanced Swift patterns. The key is to keep the expression clear.

### 1. Using the Ternary Operator with Computed Properties

A computed property is a property that calculates its value instead of storing it directly.

```swift
struct Product {
    let name: String
    let stock: Int

    var stockStatus: String {
        stock > 0 ? "Available" : "Sold out"
    }
}

let book = Product(name: "Swift Basics", stock: 3)

print(book.stockStatus)
// Output: Available
```

Output (tested with Swift 6.4):

```text
Available
```

### 2. Using the Ternary Operator with Enum Values

An enum, short for enumeration, defines a group of related values. You can use the ternary operator to choose an enum case.

```swift
enum AccountLevel {
    case free
    case premium
}

let hasPaid = true

let level: AccountLevel = hasPaid ? .premium : .free

print(level)
// Output: premium
```

Output (tested with Swift 6.4):

```text
premium
```

### 3. Using the Ternary Operator with Closures

A closure is a block of code that can be stored and passed around. You can use the ternary operator to choose between two closures when both closures have the same type.

```swift
let shouldUppercase = true

let formatter: (String) -> String = shouldUppercase
    ? { text in text.uppercased() }
    : { text in text.lowercased() }

print(formatter("Swift"))
// Output: SWIFT
```

Output (tested with Swift 6.4):

```text
SWIFT
```

This is more advanced because the ternary operator is choosing behavior, not just a text or number value.

### 4. Using the Ternary Operator with Function Arguments

The ternary operator can make function calls more compact when only one argument changes.

```swift
func showAlert(title: String, message: String) {
    print("\(title): \(message)")
}

let didSave = true

showAlert(
    title: didSave ? "Success" : "Error",
    message: didSave ? "Your changes were saved." : "Please try again."
)

// Output: Success: Your changes were saved.
```

Output (tested with Swift 6.4):

```text
Success: Your changes were saved.
```

## Comparing Related Concepts

### Ternary Operator vs Nil-Coalescing Operator

The ternary operator and nil-coalescing operator can sometimes look similar, but they solve different problems.

| Concept | Syntax | Use It When | Example |
| --- | --- | --- | --- |
| Ternary operator | `condition ? a : b` | You have a true-or-false condition | `age >= 18 ? "Adult" : "Minor"` |
| Nil-coalescing operator | `optional ?? defaultValue` | You want a default value if an optional is nil | `name ?? "Guest"` |

### Beginner Approach vs Better Approach

| Situation | Beginner Approach | Better Approach | Why |
| --- | --- | --- | --- |
| Choosing between two short strings | Long `if` statement | Ternary operator | Shorter and still readable |
| Running several actions | Ternary operator | `if` statement | Clearer for multi-step logic |
| Providing a default optional value | Ternary with force unwrap | Nil-coalescing operator | Safer and simpler |
| Choosing from many cases | Deep nested ternary | `if`, `switch`, or a helper function | Better readability |

## Key Points

- The ternary operator chooses between two values based on a condition.
- Its syntax is `condition ? valueIfTrue : valueIfFalse`.
- The condition must evaluate to a Boolean value.
- The true and false results should usually be compatible types.
- The ternary operator is an expression, so it can be assigned, returned, or passed as an argument.
- Use it for simple choices, not complex logic.
- Avoid unnecessary expressions like `condition ? true : false`.
- For optional default values, prefer the nil-coalescing operator `??`.

## Best Practices, Limitations, and Common Mistakes

### Best Practices

- Use the ternary operator when choosing between two simple values.
- Keep ternary expressions short enough to understand quickly.
- Use clear variable names so the condition is easy to read.
- Break long ternary expressions across multiple lines if needed.
- Use `if` statements when the logic requires multiple steps.
- Use `??` when working with optional default values.

### Limitations

- The ternary operator only chooses between two branches at a time.
- Nested ternary expressions can become hard to read.
- It is not ideal for logic that performs several actions.
- It can make debugging harder if too much logic is placed on one line.

### Performance Considerations

For normal Swift code, the ternary operator does not provide a meaningful performance advantage over an `if` statement. Choose it for clarity and conciseness, not speed.

Performance only becomes important if the expressions on either side do expensive work, such as loading data, performing large calculations, or calling complex functions.

### Common Mistakes

- Using the ternary operator for complex business logic.
- Forgetting the colon after the true result.
- Mixing unclear result types.
- Writing unnecessary Boolean ternary expressions.
- Using force unwraps with optionals when a safer operator would work.

### How to Avoid Mistakes

- Use the ternary operator only when the expression is easy to read aloud.
- Check that both result values represent the same kind of data.
- Use parentheses when they improve readability.
- Replace nested ternary expressions with `if` or `switch` when the logic grows.

> Tip: If you need several sentences to explain a ternary expression, it probably should be an `if` statement instead.

## Practical Example

Imagine you are building a simple shopping app. The app needs to show a message based on the user’s cart total. If the total is at least `100`, the user gets free shipping. Otherwise, the app shows how much more the user needs to spend.

```swift
let cartTotal = 75
let freeShippingMinimum = 100

let amountNeeded = freeShippingMinimum - cartTotal

let shippingMessage = cartTotal >= freeShippingMinimum
    ? "You qualify for free shipping!"
    : "Add $\(amountNeeded) more to get free shipping."

print(shippingMessage)
// Output: Add $25 more to get free shipping.
```

Output (tested with Swift 6.4):

```text
Add $25 more to get free shipping.
```

The condition is `cartTotal >= freeShippingMinimum`. Because `cartTotal` is `75` and the minimum is `100`, the condition is false. Swift chooses the message after the colon.

## Summary

The ternary operator in Swift is a compact way to choose between two values. It uses a condition, a value for the true case, and a value for the false case.

It is useful for assignments, function returns, function arguments, computed properties, simple SwiftUI values, and short display logic. However, it should be used carefully. When the logic becomes long, nested, or difficult to understand, an `if` statement or `switch` statement is usually better.

The best Swift code is not always the shortest code. The best code is clear, safe, and easy to maintain.

## Practice Exercise

### Question

You are building a small fitness app. The app stores a user’s daily step count. If the user walks at least `10000` steps, show `"Goal reached"`. Otherwise, show how many more steps the user needs to reach the goal.

Create a Swift program that:

- Stores the user’s current steps in a constant named `steps`.
- Stores the daily goal in a constant named `dailyGoal`.
- Calculates the remaining steps.
- Uses the ternary operator to create a message.
- Prints the message.

Use this value for the exercise:

```swift
let steps = 7500
```

### Expected Output:

```swift
You need 2500 more steps to reach your goal.
```

### Hint:

First subtract `steps` from `dailyGoal` to calculate the remaining steps. Then use the ternary operator to choose between the success message and the remaining steps message.

### Solution:

```swift
let steps = 7500
let dailyGoal = 10000

let remainingSteps = dailyGoal - steps

let message = steps >= dailyGoal
    ? "Goal reached"
    : "You need \(remainingSteps) more steps to reach your goal."

print(message)
// Output: You need 2500 more steps to reach your goal.
```

Output (tested with Swift 6.4):

```text
You need 2500 more steps to reach your goal.
```

### Explanation

1. `steps` stores the user’s current step count.
2. `dailyGoal` stores the target number of steps.
3. `remainingSteps` calculates how many more steps are needed.
4. The ternary operator checks whether `steps >= dailyGoal`.
5. Since `7500` is less than `10000`, Swift prints the message after the colon.

> Tip: Try changing `steps` to `12000` and run the code again. The output should change to `Goal reached`.
