Contains Over First

ID

swift.contains_over_first

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

Swift

Tags

collection, efficiency

Description

Reports the .first(where: …​) != nil (or == nil) shape. When you only need to test existence, use .contains(where:) — it expresses intent more clearly and avoids the optional-binding noise.

xs.first(where: { ... }) != nil       // FLAW
xs.first(where: { ... }) == nil       // FLAW

xs.contains(where: { ... })           // OK

// OK — using the bound element, not just existence.
if let m = xs.first(where: { ... }) {
    use(m)
}

Rationale

.first(where:) constructs and returns an Optional even when the caller only cares whether a match exists. .contains(where:) returns a Bool directly, makes the intent explicit, and gives the compiler a cleaner signal to optimise the lookup.

Remediation

let hasAny = xs.contains(where: { ... })