Sorting By Functions in Swift

Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in Swift.

import Foundation

func main() {
    var fruits = ["peach", "banana", "kiwi"]

    // We implement a comparison function for string lengths.
    let lenCmp = { (a: String, b: String) -> Bool in
        return a.count < b.count
    }

    // Now we can call `sorted(by:)` with this custom
    // comparison function to sort `fruits` by name length.
    fruits.sort(by: lenCmp)
    print(fruits)

    // We can use the same technique to sort an array of
    // values that aren't built-in types.
    struct Person {
        let name: String
        let age: Int
    }

    var people = [
        Person(name: "Jax", age: 37),
        Person(name: "TJ", age: 25),
        Person(name: "Alex", age: 72)
    ]

    // Sort `people` by age using `sorted(by:)`.
    // Note: if the `Person` struct is large,
    // you may want the array to contain `Person` instead
    // and adjust the sorting function accordingly. If in
    // doubt, benchmark!
    people.sort { $0.age < $1.age }
    print(people)
}

main()

To run the program, save it as sorting_by_functions.swift and use swift command:

$ swift sorting_by_functions.swift
["kiwi", "peach", "banana"]
[Person(name: "TJ", age: 25), Person(name: "Jax", age: 37), Person(name: "Alex", age: 72)]

In this Swift version, we use the sort(by:) method to sort arrays in-place. For custom types like Person, we can use a closure directly in the sort method call. Swift’s standard library provides powerful and flexible sorting capabilities, making it easy to implement custom sorting logic.