Sorting helps organize data so it's easier to find or use. Custom comparators let you decide exactly how to sort things, like by size or color.
Sorted and custom comparators in Swift
let sortedArray = array.sorted(by: { (a, b) -> Bool in return a < b })
The sorted(by:) method takes a closure that compares two items.
The closure returns true if the first item should come before the second.
let numbers = [3, 1, 4, 2] let sortedNumbers = numbers.sorted(by: { $0 < $1 }) print(sortedNumbers)
let words = ["apple", "banana", "cherry"] let sortedWords = words.sorted(by: { $0.count < $1.count }) print(sortedWords)
struct Person { let name: String let age: Int } let people = [ Person(name: "Alice", age: 30), Person(name: "Bob", age: 25), Person(name: "Charlie", age: 35) ] let sortedByAge = people.sorted(by: { $0.age < $1.age }) for person in sortedByAge { print("\(person.name): \(person.age)") }
This program sorts a list of products by their price from lowest to highest and prints each product with its price.
struct Product { let name: String let price: Double } let products = [ Product(name: "Book", price: 12.99), Product(name: "Pen", price: 1.99), Product(name: "Laptop", price: 999.99), Product(name: "Coffee", price: 3.49) ] // Sort products by price, cheapest first let sortedProducts = products.sorted(by: { $0.price < $1.price }) for product in sortedProducts { print("\(product.name): $\(product.price)") }
You can use shorthand argument names like $0 and $1 for simpler code.
Sorting does not change the original array; it returns a new sorted array.
Custom comparators let you sort by any rule you want, not just natural order.
Use sorted(by:) to sort arrays with your own rules.
The comparator closure decides the order by returning true or false.
Sorting helps organize data to make it easier to use or display.
Practice
sorted(by:) method do in Swift?Solution
Step 1: Understand the purpose of
This method sorts elements of an array based on a closure that defines the order.sorted(by:)Step 2: Compare with other array methods
Unlike filtering or reversing,sorted(by:)changes order based on a custom rule.Final Answer:
It sorts an array using a custom rule you provide. -> Option AQuick Check:
sorted(by:)= custom sorting [OK]
- Confusing sorting with filtering
- Thinking it removes duplicates
- Assuming it reverses the array
sorted(by:)?Solution
Step 1: Understand sorting order
To sort descending, the comparator must return true when the first element is greater than the second.Step 2: Check each option
let sortedArray = numbers.sorted(by: { $0 > $1 }) uses { $0 > $1 } which sorts descending. let sortedArray = numbers.sorted(by: { $0 < $1 }) sorts ascending. let sortedArray = numbers.sorted() sorts ascending by default. let sortedArray = numbers.sorted(by: { $1 > $0 }) reverses the comparison incorrectly.Final Answer:
let sortedArray = numbers.sorted(by: { $0 > $1 }) -> Option DQuick Check:
Descending sort uses $0 > $1 [OK]
- Using $0 < $1 for descending
- Forgetting to provide closure for custom order
- Confusing parameter order in closure
let names = ["Anna", "Bob", "Charlie"]
let sortedNames = names.sorted(by: { $0.count < $1.count })
print(sortedNames)Solution
Step 1: Understand the sorting rule
The closure sorts by string length ascending: shorter names come first.Step 2: Apply sorting to the array
"Bob" has 3 letters, "Anna" 4, "Charlie" 7. So order is ["Bob", "Anna", "Charlie"].Final Answer:
["Bob", "Anna", "Charlie"] -> Option BQuick Check:
Sort by length ascending = ["Bob", "Anna", "Charlie"] [OK]
- Sorting alphabetically instead of by length
- Confusing < with > in closure
- Expecting original order
let items = [("a", 3), ("b", 1), ("c", 2)]
let sortedItems = items.sorted(by: { $0.1 > $1.1 })
print(sortedItems)Solution
Step 1: Check tuple access syntax
Accessing tuple elements by $0.1 and $1.1 is correct in Swift closures.Step 2: Verify sorting closure logic
The closure returns true if first element's second value is greater, sorting descending by second value.Final Answer:
There is no error; the code sorts descending by second value. -> Option AQuick Check:
Tuple access and Bool return are correct [OK]
- Thinking tuple elements can't be accessed by index
- Expecting closure to return Int
- Confusing ascending and descending order
let people = [["name": "Alice", "age": 30], ["name": "Bob", "age": 25], ["name": "Charlie", "age": 30]]. How do you sort this array first by age ascending, then by name ascending if ages are equal?Solution
Step 1: Understand sorting by multiple keys
Sorting by age ascending, then name ascending means comparing tuples of (age, name).Step 2: Check each option's logic
people.sorted { ($0["age"] as! Int, $0["name"] as! String) < ($1["age"] as! Int, $1["name"] as! String) } compares tuples directly, which sorts by age first, then name if ages equal. people.sorted { $0["age"] as! Int < $1["age"] as! Int && $0["name"] as! String < $1["name"] as! String } uses && which fails for correct ordering. people.sorted(by: { $0["age"] as! Int > $1["age"] as! Int || $0["name"] as! String > $1["name"] as! String }) sorts descending and mixes conditions incorrectly. people.sorted(by: { $0["name"] as! String < $1["name"] as! String }) sorts only by name.Final Answer:
people.sorted { ($0["age"] as! Int, $0["name"] as! String) < ($1["age"] as! Int, $1["name"] as! String) } -> Option CQuick Check:
Tuple comparison sorts by multiple keys [OK]
- Using && instead of tuple comparison
- Sorting only by one key
- Mixing ascending and descending incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
