0
0
Swiftprogramming~5 mins

Sorted and custom comparators in Swift

Choose your learning style9 modes available
Introduction

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.

When you want to list names in alphabetical order.
When you need to sort numbers from smallest to largest.
When sorting objects by a specific property, like sorting people by age.
When you want to sort items in a special way, like putting favorites first.
Syntax
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.

Examples
Sorts numbers in ascending order using a simple closure.
Swift
let numbers = [3, 1, 4, 2]
let sortedNumbers = numbers.sorted(by: { $0 < $1 })
print(sortedNumbers)
Sorts words by their length, shortest first.
Swift
let words = ["apple", "banana", "cherry"]
let sortedWords = words.sorted(by: { $0.count < $1.count })
print(sortedWords)
Sorts a list of people by their age from youngest to oldest.
Swift
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)")
}
Sample Program

This program sorts a list of products by their price from lowest to highest and prints each product with its price.

Swift
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)")
}
OutputSuccess
Important Notes

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.

Summary

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.