Same Condition
ID |
swift.same_condition |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Swift |
Tags |
code_smell, switch |
Description
Reports an if / else if / else if … chain whose every branch
tests the same subject with ==. A switch expresses the intent more
clearly and — when the subject is an enum — surfaces a compile-time
error if a new case is added but the chain is not updated.
if state == .idle { ... } // FLAW (whole chain)
else if state == .busy { ... }
else if state == .done { ... }
Rationale
if-chains are general-purpose; a reader has to parse each branch to
discover that they all compare the same value. switch makes the
shape explicit and lets the compiler enforce exhaustiveness for enums,
catching bugs where a new case slips in unhandled.
When not to fire
The rule is conservative and only fires when:
-
the chain has at least one
else if(two or more branches); -
every branch has a single condition that is
<subject> == <rhs>; -
the left-hand-side text is identical across all branches.
Chains containing if let, if case, #available, !=, &&, or
mixed subjects are skipped — switch would not be a clean replacement
for those shapes.