In Swift, is sorted(by:) a stable sort, and what must its areInIncreasingOrder closure guarantee for the result to be correct?
answer
- equal keys keep arrival order
- documented since Swift 5.8
- strict weak ordering
- less-than, never less-or-equal
basics
~10 sYes: Swift documents sort() and sorted(by:) as stable, so elements the predicate does not order keep their original relative order. The predicate must be a strict weak ordering, so less-or-equal comparisons break the guarantee.
solid answer
~40 sThe standard library's doc comment says the sorting algorithm is guaranteed to be stable: elements for which `areInIncreasingOrder` establishes no order keep their original relative order. The implementation was stable before Swift 5; SE-0372 made the guarantee official in Swift 5.8. The predicate must be a **strict weak ordering**: `areInIncreasingOrder(a, a)` is always `false`, and both ordering and incomparability are transitive. `{ $0.hour < $1.hour }` qualifies; `{ $0.hour <= $1.hour }` does not, because it returns `true` for equal hours, and the documented guarantees no longer apply. In a test with Swift 6.4, sorting a log with `<=` reversed events with equal hours. `sorted(by:)` works on any `Sequence` and returns an `Array` in O(*n* log *n*); `sort(by:)` sorts a mutable random-access collection in place.
code
swift · 15 linesstruct LoggedEvent { let name: String; let hour: Int }
// Already in log order (arrival order)
let log = [
LoggedEvent(name: "login-a", hour: 9),
LoggedEvent(name: "crash-1", hour: 14),
LoggedEvent(name: "login-b", hour: 9),
LoggedEvent(name: "crash-2", hour: 14),
]
let byHour = log.sorted { $0.hour < $1.hour }
print(byHour.map(\.name)) // ["login-a", "login-b", "crash-1", "crash-2"]
let broken = log.sorted { $0.hour <= $1.hour }
print(broken.map(\.name))go deeper
Recall that sorted returns a new array, sort sorts in place, and that the closure answers whether the first argument comes before the second.
Explain stability, the three strict weak ordering rules, and why less-or-equal violates irreflexivity and voids the guarantees.
Catch comparators that use <=, inconsistent keys or random tiebreakers in review, and know that stability is a documented promise only since Swift 5.8.
Decide where ordering must be deterministic across the app (timelines, exports, tests) and make stable sorts with explicit tiebreakers the team default there.
## What stable means A sort is **stable** when elements that compare as equal (more precisely, elements the predicate does not order relative to each other) stay in the order they had before sorting. In the analytics scenario a day's log arrives in time order; sorting it by hour bucket with a stable sort keeps the events inside each hour in arrival order, which is what a timeline view expects. Swift's `sort()`, `sort(by:)`, `sorted()` and `sorted(by:)` all carry the same sentence in their doc comments: the sorting algorithm is **guaranteed to be stable**. The history matters when you read older answers: - The implementation became stable before Swift 5. - Until Swift 5.8 the documentation still said the sort was *not* guaranteed to be stable. - **SE-0372**, implemented in Swift 5.8, changed the documentation to make stability a promise you can rely on. ## The predicate contract: strict weak ordering `areInIncreasingOrder` answers "must the first argument come before the second?". The doc comment requires it to be a **strict weak ordering**, defined by three rules for any `a`, `b`, `c`: 1. **Irreflexivity:** `areInIncreasingOrder(a, a)` is always `false`. 2. **Transitive comparability:** if `a` comes before `b` and `b` before `c`, then `a` comes before `c`. 3. **Transitive incomparability:** if neither of `a`, `b` comes before the other, and the same holds for `b`, `c`, then the same holds for `a`, `c`. `<` and `>` on `Comparable` types satisfy these rules. `<=` and `>=` break irreflexivity: they say an element must come before itself, and before every equal element in both directions. ## What goes wrong with <= The documentation states what the predicate must be and does not describe what happens otherwise, so a broken predicate leaves you outside every promise, stability included. A concrete run with Swift 6.4: | Predicate | Input order | Result | |---|---|---| | `{ $0.hour < $1.hour }` | login-a 9, crash-1 14, login-b 9, crash-2 14 | login-a, login-b, crash-1, crash-2 | | `{ $0.hour <= $1.hour }` | same | login-b, login-a, crash-2, crash-1 | The hours are still grouped, but every pair of equal-hour events came out reversed. Tests with distinct keys pass, and the bug appears only on real data with ties, which makes it a classic review catch. A comparator built from a computed property that is not consistent across calls, such as a random tiebreaker or a value that changes during the sort, breaks the same contract. ## sorted versus sort - `sorted()` and `sorted(by:)` are defined on `Sequence` and return a new `Array`. Calling them on a `Set` or `Dictionary` is the usual way to get a deterministic order, and the result is an array, not a set. - `sort()` and `sort(by:)` mutate in place and are available on collections that are both `MutableCollection` and `RandomAccessCollection`, such as `Array`. - `sorted()` is equivalent to `sorted(by: <)`; pass `>` for descending order. - All of them are documented as O(*n* log *n*). - The `by:` variants are `rethrows`, so a throwing comparator works with `try`. ## Using stability deliberately Because the sort is stable, sorting by a secondary key first and then by the primary key gives a correct multi-key order. In practice one comparator that compares the primary key and breaks ties on the secondary is clearer and sorts once; comparing several keys at once, with tuples or key paths, is covered in the Swift lesson on `Comparable` and ordering. Stability is still what lets you sort an already time-ordered log by a coarse key without losing the time order inside each bucket. ## Review checklist for comparators - The comparator uses `<` or `>`, never `<=` or `>=`. - It reads only stable data: no random values, no state that changes while the sort runs. - Ties are either broken explicitly or left to stability on purpose, with the input order known. - Expensive keys (a date parsed from a string, a localized name) are computed once before sorting, for example by mapping to pairs, rather than on every one of the O(*n* log *n*) comparisons.
- If stability was implemented before Swift 5, why does SE-0372 matter?Until Swift 5.8 the documentation explicitly said the sort was not guaranteed to be stable, so relying on it was relying on an implementation detail that could change. SE-0372 turned the behaviour into a documented guarantee, which is what makes code that depends on it correct rather than lucky.
- How would you sort events by hour, newest hour first, keeping arrival order inside each hour?Use `log.sorted { $0.hour > $1.hour }`. `>` is a strict weak ordering, so stability still holds: events with the same hour keep their original relative order. Writing `>=` breaks the contract, and equal hours may then come out reversed.
- Swift's sort is not stable, so equal elements end up in arbitrary order
- Using <= in sorted(by:) is harmless because equal elements are equal anyway
- sorted() on a Set returns a Set in sorted order
- sort(by:) and sorted(by:) differ only in speed, not in what they return
- Stability depends on the input size, small arrays only