0
0
Swiftprogramming~3 mins

Why Sorted and custom comparators in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could sort any list exactly how you want with just one simple line of code?

The Scenario

Imagine you have a messy list of names or numbers, and you want to put them in order by hand. You try to compare each item one by one, writing lots of code to check who comes first or which number is bigger.

The Problem

Doing this manually is slow and confusing. You might forget a rule or make mistakes, especially if the sorting rules are tricky, like sorting by last name, then first name, or sorting numbers in a special way.

The Solution

Using sorted functions with custom comparators lets you tell the computer exactly how to compare items. It handles all the hard work quickly and correctly, so you get a neat, ordered list without the headache.

Before vs After
Before
var sortedList = list
for i in 0..<sortedList.count {
  for j in i+1..<sortedList.count {
    if sortedList[i] > sortedList[j] {
      let temp = sortedList[i]
      sortedList[i] = sortedList[j]
      sortedList[j] = temp
    }
  }
}
After
let sortedList = list.sorted { $0 < $1 }
What It Enables

You can easily sort complex data exactly how you want, making your programs smarter and your code cleaner.

Real Life Example

Think about sorting a contact list by last name, then by first name, or sorting products by price and rating to show the best options first.

Key Takeaways

Manual sorting is slow and error-prone.

Custom comparators let you define clear sorting rules.

Sorted functions make ordering data easy and reliable.