Comparable and Sorting
Define ordering with < for sorting.
Comparable and Sorting is a free Swift Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.
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)) // trueSorting 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 30Multi-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:
Comparableprovides 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.
Learn Swift with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 122
- Lessons
- 409
Frequently Asked Questions
Is the “Comparable and Sorting” lesson free?
Yes — any 3 lessons of the Swift Academy learning path, including “Comparable and Sorting”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.
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
- Synthesized Equatable
- Hashable and hash(into:)
- Comparable and Sorting
- Custom Equality Semantics