Chapter 68: Swift Sorting

1. The Big Picture: What does “sorting” mean in Swift?

Sorting means rearranging the elements of a collection so they appear in a specific order.

Most common orders people want:

  • Ascending (small → big): 1, 3, 7, 12, 25
  • Descending (big → small): 25, 12, 7, 3, 1
  • Alphabetical (A → Z): Apple, Banana, Mango, Orange
  • Reverse alphabetical (Z → A)
  • Custom order (e.g. by priority, by distance, by recency, by user rating…)

Swift gives you very elegant and type-safe ways to sort.

The two most important methods you will use every single day:

  1. sorted() → returns a new sorted array (original unchanged)
  2. sort() → sorts the array in place (modifies the original)

2. The simplest & most common cases

Case 1 – Sorting numbers (ascending by default)

Swift

Descending order (very common):

Swift

Real tip: > is actually a function (Int, Int) -> Bool — that’s why it works directly.

Case 2 – Sorting strings (alphabetical)

Swift

Case-insensitive sorting (very important in real apps):

Swift

3. Sorting custom types (structs / classes) — this is where it gets really useful

Almost every real app needs to sort objects, not just numbers or strings.

Step 1 – Make your type comparable (the cleanest way)

Swift

Output:

text

Step 2 – Sort by multiple criteria (very common)

Swift

Shorter version (using tuple comparison):

Swift

4. Real-life examples you will actually write

Example 1 – Leaderboard / high scores (games, quizzes)

Swift

Example 2 – Sort products by price, then by name

Swift

5. Very Common Beginner Mistakes & Fixes

Mistake Wrong / Dangerous code Correct / Better habit Why?
Mutating array while sorting array.sort { … } then keep using old reference let sorted = array.sorted { … } sort() mutates, sorted() returns new
Force-unwrapping inside sort closure sorted { $0!.score < $1!.score } Use compactMap first or optional chaining Crash if any nil
Sorting optional values without handling nil sorted { $0 < $1 } on [Int?] sorted { $0 ?? 0 < $1 ?? 0 } or filter nils nil crashes comparison
Wrong comparator direction sorted { $0.score < $1.score } for descending sorted { $0.score > $1.score } Easy to mix up ascending/descending
Not using sorted(by:) when logic is complex sorted() on custom type sorted { a, b in … } with clear rules Default Comparable may not be what you want

6. Quick Reference – Sorting cheat sheet

Goal Most idiomatic code Notes / Tip
Numbers ascending array.sorted() or array.sorted(by: <) Default is ascending
Numbers descending array.sorted(by: >) Very common
Strings case-insensitive sorted { $0.lowercased() < $1.lowercased() } Handles “Apple” vs “banana” correctly
Custom struct by one property sorted { $0.score > $1.score } Descending score
Custom struct by multiple properties sorted { ($0.score, $0.age) > ($1.score, $1.age) } Score descending, then age ascending
Keep original unchanged let sorted = array.sorted { … } sorted() returns new array
Sort in place (modify original) array.sort { … } Use only when you don’t need the old order

7. Small Practice – Try these

  1. Create array of 6 numbers → Sort them ascending → Sort them descending
  2. Create array of 5 names (mixed case) → Sort them alphabetically (case-insensitive)
  3. Create array of structs: struct Product { let name: String; let price: Double } → Sort by price ascending, then by name alphabetical if prices equal

Paste your code here if you want feedback or want to see even cleaner versions!

What would you like to explore next?

  • Sorting with multiple criteria in more depth
  • Sorting custom types with Comparable conformance
  • Sorting in SwiftUI (sorted lists, @State updates)
  • Array slicing & memory behavior
  • Collections in SwiftUI (List, ForEach, diffable data sources)
  • Or move to another topic (dictionaries, sets, optionals, switch…)

Just tell me — we’ll continue in the same clear, detailed, patient style 😊

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *