Last Where

ID

swift.last_where

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

Swift

Tags

collection, efficiency

Description

Reports the .filter(…​).last chain. Use .last(where:) instead — it scans from the end of the collection without materialising the filtered sequence.

xs.filter { $0 > 5 }.last         // FLAW
xs.last(where: { $0 > 5 })        // OK
xs.last                           // OK — plain access

Rationale

For a collection where the last match is at position N - k from the start (i.e. k from the end), .filter(…​).last is O(N); .last(where:) is O(k).

Remediation

let last = xs.last(where: { $0 > 5 })