What if you could sort any list exactly how you want with just one simple line of code?
Why Sorted and custom comparators in Swift? - Purpose & Use Cases
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.
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.
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.
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 } } }
let sortedList = list.sorted { $0 < $1 }You can easily sort complex data exactly how you want, making your programs smarter and your code cleaner.
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.
Manual sorting is slow and error-prone.
Custom comparators let you define clear sorting rules.
Sorted functions make ordering data easy and reliable.