Sorted First / Last
ID |
swift.sorted_first_last |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Swift |
Tags |
collection, efficiency |
Description
Reports .sorted().first and .sorted().last. Sorting just to pick the
smallest or largest element is O(n log n) for an O(n) answer. Use
.min() / .max() (or the by: overloads).
xs.sorted().first // FLAW — use xs.min()
xs.sorted().last // FLAW — use xs.max()
xs.sorted(by: <).first // FLAW — use xs.min(by: <)
xs.min() // OK
xs.sorted() // OK if you need the whole sequence
Rationale
Sorting an entire sequence to pick a single element wastes work:
O(n log n) plus a fresh allocation for an answer that .min() /
.max() produce in O(n) with no allocation. On hot paths the
difference is easy to measure, and even on cold paths the explicit
.min() reads as the intended operation.