NEW BOOK! SwiftUI Fundamentals: The essential guide to SwiftUI core concepts and APIs. Learn more ...NEW BOOK! SwiftUI Fundamentals:Master SwiftUI core concepts and APIs. Learn more...
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 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.

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