In Swift, how do you sort contacts by last name and then first name, and what does each approach actually compare?
answer
- less-than plus equals
- tuples compare left to right
- no key-path sort in the standard library
- String order ignores locale
basics
~20 sCompare tuples in a closure, sorted { ($0.lastName, $0.firstName) < ($1.lastName, $1.firstName) }, or make Contact Comparable with that < when the order is inherent. Foundation's KeyPathComparator sorts by key paths and compares Strings localized.
solid answer
~40 s`Comparable` needs `<` and `==` forming a strict total order; Swift synthesizes it only for enums, so for a struct you write `<` yourself. For a one-off order, `sorted(by:)` with a **tuple comparison** is the idiom: tuples of two to six `Comparable` elements compare lexicographically, so `($0.lastName, $0.firstName) < ($1.lastName, $1.firstName)` breaks ties on the second key. The standard library has no key-path sort overload; Foundation's `KeyPathComparator` with `sorted(using:)` (iOS 15 and macOS 12) takes several key paths in order. They compare `String` differently: `String`'s `<` is locale-insensitive Unicode ordering, so "Okafor" sorts before "de Vries", while `KeyPathComparator` on a `String` key path defaults to `.localizedStandard`.
code
swift · 27 linesimport Foundation
struct Contact {
var firstName: String
var lastName: String
}
let contacts = [
Contact(firstName: "Mia", lastName: "Okafor"),
Contact(firstName: "Ana", lastName: "Lima"),
Contact(firstName: "Ben", lastName: "Okafor"),
Contact(firstName: "Zoe", lastName: "de Vries"),
]
// Tuples of two to six Comparable elements compare lexicographically.
let byTuple = contacts.sorted {
($0.lastName, $0.firstName) < ($1.lastName, $1.firstName)
}
print(byTuple.map(\.lastName)) // ["Lima", "Okafor", "Okafor", "de Vries"]
// Foundation: key-path comparators, applied in order.
// For String key paths the default comparator is .localizedStandard.
let byKeyPaths = contacts.sorted(using: [
KeyPathComparator(\Contact.lastName),
KeyPathComparator(\Contact.firstName),
])
print(byKeyPaths.map(\.lastName)) // ["de Vries", "Lima", "Okafor", "Okafor"]go deeper
Recall the tuple trick for two keys and that a struct needs a hand-written < to be Comparable.
Explain lexicographic tuple comparison, its two-to-six-element limit, and when a Comparable conformance beats a closure at the call site.
Catch the production surprises: names sorted by Unicode order instead of the user's locale, and a < that disagrees with == breaking the strict-total-order promise.
Choose one sorting policy for user-facing names, localized comparison through a shared comparator, so screens do not each pick their own order.
## What Comparable promises `Comparable` refines `Equatable`. A conforming type implements `<` and `==`, and the standard library supplies `>`, `<=` and `>=` from them. The documentation requires a **strict total order**: for any two values exactly one of `a == b`, `a < b` or `b < a` holds, and `<` must be irreflexive (`a < a` is false), asymmetric and transitive. Exceptional values may opt out; `Double.nan` compares as neither less than, greater than nor equal to ordinary numbers. The compiler synthesizes `Comparable` only for enums without a raw type, ordered by case declaration (Swift 5.3). For a struct you get `automatic synthesis of 'Comparable' is not supported for struct declarations`, so a contacts model needs a hand-written `<`. ## Tuple comparison: the multi-key idiom The standard library defines `==`, `<`, `<=`, `>` and `>=` for tuples of **two to six** elements whose elements are `Comparable`. The comparison is **lexicographic**: it compares the first components and only looks at the second when the first are equal. ```swift contacts.sorted { ($0.lastName, $0.firstName) < ($1.lastName, $1.firstName) } ``` That one line replaces the nested `if lhs.lastName != rhs.lastName` ladder. Useful variations: - **Descending on one key:** swap that key's operands, as in `($1.lastName, $0.firstName) < ($0.lastName, $1.firstName)`. - **More than six keys:** tuple operators stop at six elements, so write the comparison out or compose comparators. - **Optional keys:** `Optional` is not `Comparable`, so map a missing value to a sentinel such as `""` before it goes into the tuple. The standard library's sort is guaranteed stable, so elements whose keys compare equal keep their incoming order. ## Comparable conformance or a closure? | Approach | When it fits | Cost | |---|---|---| | `Contact: Comparable` with a tuple-based `<` | the order is the type's natural one and many call sites need it | every `sorted()`, `min()` and `max()` uses it; `<` must agree with `==` | | `sorted(by:)` with a tuple closure | one screen's order, such as "by company" | repeated at each call site unless wrapped in a helper | | Foundation `KeyPathComparator` + `sorted(using:)` | orders chosen at run time, such as user-selected columns | Foundation dependency; `String` keys compare localized by default | When the name order really is the type's natural order, the conformance is a few lines, and declaring `Comparable` in the same file also gets `==` synthesized, because `Comparable` refines `Equatable`: ```swift extension Contact: Comparable { static func < (lhs: Contact, rhs: Contact) -> Bool { (lhs.lastName, lhs.firstName) < (rhs.lastName, rhs.firstName) } } ``` After that, plain `contacts.sorted()`, `contacts.min()` and `contacts.max()` all use the name order. A subtle trap with conformance: if `Contact` keeps the synthesized `==` over all properties but `<` looks only at names, two contacts with the same names but different emails are neither equal nor ordered. That breaks the "exactly one holds" rule, and generic algorithms are entitled to assume it. ## Sorting by key paths "Sort by a key path" has two meanings: 1. **A standard-library helper you write**, such as `sorted(by: \.lastName)` defined in an extension that reads `$0[keyPath: keyPath] < $1[keyPath: keyPath]`. The standard library itself only offers `sorted()` and `sorted(by:)`. 2. **Foundation's `KeyPathComparator`**, passed as an array to `sorted(using:)`. Each comparator is tried in order, so `[KeyPathComparator(\Contact.lastName), KeyPathComparator(\Contact.firstName)]` gives last name, then first name. Each takes an `order:` of `.forward` or `.reverse`. ## The String order trap Swift's `String` documentation says strings are "Unicode correct and locale insensitive". `String`'s `<` compares the strings' Unicode content lexicographically after normalizing it, so canonically equivalent strings tie, but it never consults a user's alphabet. Consequences for a contact list: - Uppercase letters sort before lowercase, so "Okafor" comes before "de Vries". - Accented initials such as "Ébert" sort after "Fox". - Digits inside names compare character by character, not numerically. `KeyPathComparator` initialized with a `String` key path uses `String.StandardComparator.localizedStandard` unless you pass another comparator, and `localizedStandardCompare(_:)` does the same in a closure. That is why the two approaches in the example print different orders for the same data. For anything a user reads, sort with the localized comparison; keep `<` for identifiers and internal keys.
- How do you sort by last name ascending but, within a family, by birth date descending?Swap the operands for the descending key only: `($0.lastName, $1.birthDate) < ($1.lastName, $0.birthDate)`. With Foundation, pass `KeyPathComparator(\.birthDate, order: .reverse)` as the second comparator. Both keep the tie-break on the second key only.
- Why might making `Contact` `Comparable` by name alone cause trouble?`Comparable` expects exactly one of `==`, `<` or `>` to hold. If `==` is synthesized over every property but `<` reads only names, two contacts with equal names and different emails are neither equal nor ordered. Either align `==` with `<`, or keep the name order as a closure.
- Why does `sorted()` put "Zoe" before "adam"?`String`'s `<` is locale-insensitive Unicode ordering, and uppercase Latin letters precede lowercase ones. For user-facing lists, compare with `localizedStandardCompare(_:)` or a `KeyPathComparator`, whose `String` default is `.localizedStandard`.
- Structs whose properties are all Comparable get a synthesized <.
- Tuple comparison works for any number of elements.
- String < sorts names the way the user's locale expects.
- The standard library has sorted(by:) that takes a key path directly.
- A < that ignores fields == compares is harmless.