0Pricing
Swift Academy · Lesson

Comparable and Sorting

Define ordering with < for sorting.

Comparable and Sorting is a free Swift Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is Comparable?

Comparable gives a type ordering operators: <, <=, >, >=. Conforming lets you call sorted(), min(), and max() directly.

Conforming with <

You only implement <; the rest are derived. (Equatable is also required.)

struct Version: Comparable {
    let major: Int
    static func < (l: Version, r: Version) -> Bool { l.major < r.major }
}
print(Version(major: 1) < Version(major: 2))  // true

Sorting a Comparable Type

With Comparable, sorted() needs no closure:

struct Score: Comparable {
    let points: Int
    static func < (l: Score, r: Score) -> Bool { l.points < r.points }
}
let sorted = [Score(points: 3), Score(points: 1), Score(points: 2)].sorted()
print(sorted.map { $0.points })  // [1, 2, 3]

min and max for Free

Comparable also enables aggregate helpers:

struct Temp: Comparable {
    let c: Int
    static func < (l: Temp, r: Temp) -> Bool { l.c < r.c }
}
let temps = [Temp(c: 20), Temp(c: 5), Temp(c: 30)]
print(temps.min()!.c, temps.max()!.c)  // 5 30

Multi-Key Ordering

For tie-breaking across several fields, compare them in priority order inside < using tuples — Swift compares tuples lexicographically.

Tuple Comparison Trick

Compare by last name, then first name:

struct Person: Comparable {
    let last: String
    let first: String
    static func < (l: Person, r: Person) -> Bool {
        (l.last, l.first) < (r.last, r.first)
    }
}
let p = [Person(last: "Lee", first: "Bo"), Person(last: "Lee", first: "An")].sorted()
print(p.map { $0.first })  // ["An", "Bo"]

Sorting Without Comparable

You can always sort with a trailing closure even if the type is not Comparable:

struct Item { let name: String; let qty: Int }
let items = [Item(name: "B", qty: 2), Item(name: "A", qty: 5)]
let byQty = items.sorted { $0.qty > $1.qty }
print(byQty.map { $0.name })  // ["A", "B"]

Descending Sort

Reverse the comparison or call .reversed():

let nums = [3, 1, 4, 1, 5]
print(nums.sorted(by: >))         // [5, 4, 3, 1, 1]
print(nums.sorted().reversed())   // [5, 4, 3, 1, 1]

sorted vs sort

sorted() returns a new array; sort() mutates in place (needs a var):

var nums = [3, 1, 2]
nums.sort()
print(nums)  // [1, 2, 3]
let copy = [3, 1, 2].sorted()
print(copy)  // [1, 2, 3]

Stable-Enough Sorting

Swift sort is guaranteed stable since Swift 5: equal elements keep their relative order. Rely on this for predictable multi-pass sorts:

let words = ["bb", "a", "cc", "d"]
let byLen = words.sorted { $0.count < $1.count }
print(byLen)  // ["a", "d", "bb", "cc"]  -- "a" before "d", "bb" before "cc"

Sorting by a Key Path

You can sort with a closure that reads any property without conforming the whole type:

struct Player { let name: String; let score: Int }
let players = [Player(name: "A", score: 30), Player(name: "B", score: 50)]
let ranked = players.sorted { $0.score > $1.score }
print(ranked.map { $0.name })  // ["B", "A"]

Quick Check

Which single operator must you implement to conform to Comparable?

Recap

You learned Comparable:

  • Comparable provides ordering operators; implement only <
  • Enables sorted(), min(), max() with no closure
  • Tuple comparison gives easy multi-key ordering
  • sorted() returns new; sort() mutates; sort is stable

Next: custom equality semantics.

Frequently asked questions

Is the “Comparable and Sorting” lesson free?

Yes — the full text of “Comparable and Sorting” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “Comparable and Sorting”?

Define ordering with < for sorting. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Comparable and Sorting” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Synthesized Equatable
  2. Hashable and hash(into:)
  3. Comparable and Sorting
  4. Custom Equality Semantics
← Back to Swift Academy