Part of Swift with Copilot

Swift with Copilot: Sort a list of numbers

Sandy LaneSandy Lane

Video: Swift with Copilot: Sort a list of numbers by Taught by Celeste AI - AI Coding Coach

Take the quiz on the full lesson page
Test what you've read · interactive walkthrough

Swift with Copilot: Sort a List of Numbers

numbers.sorted() returns a new sorted array. numbers.sort() sorts in place. Default order is ascending. Custom: sorted(by: >) for descending, or pass any closure (a, b) -> Bool.

Sorting is the canonical "you'd rather not implement this yourself" task. Swift's standard library handles it.

The Copilot prompt

// Sort a list of numbers
let numbers = [5, 2, 8, 1, 9, 3]

Copilot completes:

let numbers = [5, 2, 8, 1, 9, 3]
let sorted = numbers.sorted()
print(sorted)
// [1, 2, 3, 5, 8, 9]

sorted() vs sort()

let numbers = [5, 2, 8, 1, 9, 3]

// Returns a new sorted array; original unchanged
let sortedAsc = numbers.sorted()
print(numbers)     // [5, 2, 8, 1, 9, 3]
print(sortedAsc)   // [1, 2, 3, 5, 8, 9]

// Sort in place; needs `var`
var mutable = [5, 2, 8, 1, 9, 3]
mutable.sort()
print(mutable)     // [1, 2, 3, 5, 8, 9]

Convention across Swift's stdlib: the past-tense form (sorted, reversed, filtered) returns a new value; the imperative form (sort, reverse) mutates in place.

Why does sorted() work without arguments?

Because Int conforms to the Comparable protocol — it has < defined. Any Sequence of Comparable elements gets sorted() for free.

Same for String, Double, Date, custom types you make Comparable, etc.

Stability

Swift's sort() and sorted() are not guaranteed stable — equal elements might swap relative positions. For most use cases, this doesn't matter.

If stability matters (e.g., sorting by one field while preserving the prior order), use Swift's sortedStable (in newer versions) or sort with a tiebreaker key.

Time complexity

O(n log n) on average. Swift uses a hybrid algorithm (introsort variant). For huge arrays, you can't beat the standard library — don't try.

Common stumbles

Mutating without var. let arr = [...]; arr.sort() errors — let is immutable. Either use var or call sorted().

Comparing mixed types. [1, "a"] is [Any] — not Comparable. You can't sort heterogeneous arrays without a custom comparator.

Stale reference after sorting. Indexes change! After arr.sort(), arr[0] is the smallest, not the originally-first element.

sort() returns Void. let s = arr.sort() gives s = (). You wanted arr.sorted().

What's next

Episode 4: Sort ascending and descending. Custom comparators.

Recap

numbers.sorted() — new sorted array, ascending. numbers.sort() — in place, needs var. Works on any Comparable. O(n log n). For custom orders, pass a closure (next episode).

Next episode: ascending and descending.

Ready? Take the quiz on the full lesson page →
Test what you've learned. Watch the lesson and try the interactive quiz on the same page.