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

Rationale

Even for Array, String, and other O(1) .count collections, .isEmpty is the canonical, intent-revealing form. Using it removes a class of accidental performance bugs when the underlying collection type changes (e.g. switching from Array to a lazy filter chain).

Remediation

Use .isEmpty:

if collection.isEmpty { ... }
if !collection.isEmpty { ... }