Nested Ternary
ID |
swift.nested_ternary |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Best Practice |
Language |
Swift |
Tags |
readability, simplification |
Description
Reports a ternary expression cond ? a : b that contains another
ternary in any of its branches.
let label = x > 0
? (x > 10 ? "big" : "small")
: "neg"
let tier = x < 0 ? "neg"
: x == 0 ? "zero"
: x < 10 ? "small"
: "big"
Configuration
-
maxTernaryDepth(default1) — ternary nesting depths strictly greater than this value are flagged. The default reports any ternary inside another ternary.
Rationale
A single ternary trades a few words for terseness and is widely understood. Stacking them multiplies the cost of reading without giving anything back: the reader has to mentally re-bracket the operators (Swift’s ternary is right-associative) and remember which branch they were tracing. The defect rate of nested ternaries is high enough that almost every modern style guide either bans or strongly discourages them.
Remediation
Lift the inner ternary out into either an if/else or a small
helper. For chains of two or three categories, a switch is usually
clearer; for table-like mappings, a dictionary is even better.
func labelFor(_ x: Int) -> String {
if x < 0 { return "neg" }
if x == 0 { return "zero" }
if x < 10 { return "small" }
return "big"
}