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
- Bool Values and Expressions
- The Ternary Conditional Operator
- Avoiding Nested Ternaries
- Boolean Methods and Toggling