First Predicate

ID

swift.first_predicate

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

Swift

Tags

collection, efficiency

Description

Reports the .filter(…​).first chain. Materialising the filtered collection just to take the first element wastes work — Swift’s .first(where:) short-circuits on the first match.

xs.filter { $0.id == id }.first         // FLAW
xs.first(where: { $0.id == id })        // OK
xs.first                                // OK — plain access

Rationale

For an N-element collection where the first match is at position k, .filter(…​).first does O(N) work; .first(where:) does O(k). For hot paths or large collections this is a meaningful difference.

Remediation

let first = xs.first(where: { $0.id == id })