Sorting arrays in Swift using comparison operators as closures
Sorting arrays in Swift can be made more concise and readable by using comparison operators as closures. Swift’s sorted(by:)
method allows us to pass operators like <
or >
directly, leveraging their ability to compare elements.
For example:
let numbers = [3, 1, 4, 1, 5, 9, 2]
// [1, 1, 2, 3, 4, 5, 9]
let ascending = numbers.sorted(by: <)
// [9, 5, 4, 3, 2, 1, 1]
let descending = numbers.sorted(by: >)
Here, <
and >
act as shorthand for closures, making the code more expressive and easier to understand. This technique elegantly utilizes Swift’s functional programming capabilities.
You can learn more about Sorting arrays using comparison operators as closures and many other Swift techniques in my book Swift Gems. It offers 100+ advanced Swift tips, from optimizing collections and leveraging generics, to async patterns, powerful debugging techniques, and more - each designed to make your code clearer, faster, and easier to maintain.