Quick Tip Icon
Quick Tip

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 covers a wide range of topics, including optimizing collections, handling strings, mastering asynchronous programming, and debugging. Get your copy and let's explore these advanced techniques together.

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Level up your Swift skills!$35

100+ tips to take your Swift code to the next level

Swift Gemsby Natalia Panferova

  • Advanced Swift techniques for experienced developers bypassing basic tutorials
  • Curated, actionable tips ready for immediate integration into any Swift project
  • Strategies to improve code quality, structure, and performance across all platforms

Level up your Swift skills!

100+ tips to take your Swift code to the next level

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Swift Gems

by Natalia Panferova

$35