Avoiding Nested Ternaries
Keep conditional logic readable and maintainable.
When Ternaries Help
A single ternary is clean and readable for a simple two-way choice. The trouble starts when you nest one ternary inside another.
let temp = 10
let label = temp < 0 ? "Freezing" : "Above zero"
print(label)A Nested Ternary
You can nest ternaries to handle more than two cases, but the result quickly becomes hard to read.
let score = 75
let grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F"
print(grade)All lessons in this course
- Bool Values and Expressions
- The Ternary Conditional Operator
- Avoiding Nested Ternaries
- Boolean Methods and Toggling