0Pricing
Swift Academy · Lesson

The Ternary Conditional Operator

Choose between two values concisely.

What Is the Ternary Operator

The ternary conditional operator chooses between two values based on a condition. Its form is condition ? valueIfTrue : valueIfFalse.

It is a compact alternative to a simple if/else.

let isMember = true
let price = isMember ? 8 : 12
print(price)

How It Reads

Read the ternary as a question: "Is the condition true? If yes, use the first value, otherwise use the second."

let temperature = 30
let message = temperature > 25 ? "Hot" : "Mild"
print(message)

All lessons in this course

  1. Bool Values and Expressions
  2. The Ternary Conditional Operator
  3. Avoiding Nested Ternaries
  4. Boolean Methods and Toggling
← Back to Swift Academy