Avoid Comparing Count To Zero
ID |
swift.avoid_comparing_count_zero |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Swift |
Tags |
collection, efficiency |
Description
Reports comparing a collection’s .count with 0 (in either direction).
Prefer .isEmpty / !.isEmpty. The isEmpty property is O(1) for
every conforming Collection, while .count may be O(n) for lazily
evaluated sequences (LazySequence, filtered collections).
if a.count == 0 { ... } // FLAW — use a.isEmpty
if a.count != 0 { ... } // FLAW — use !a.isEmpty
if a.count > 0 { ... } // FLAW — use !a.isEmpty
if 0 == a.count { ... } // FLAW
if a.isEmpty { ... } // OK
if a.count == 2 { ... } // OK — comparing to non-zero