How to sort an Array based on a property of an element in Swift

donnywals

Donny Wals

Posted on February 25, 2020

How to sort an Array based on a property of an element in Swift

The easiest way to sort an Array in Swift is to use the sort method. This method is available for all Arrays that have Equatable elements and it sorts your array in place:

var words = ["hello", "world", "this", "is", "a", "list", "of", "strings"]
words.sort() // words is now ["a", "hello", "is", "list", "of", "strings", "this", "world"]
Enter fullscreen mode Exit fullscreen mode

This modifies the input Array and sorts its elements using String conformance to Equatable.

But what if you want to sort the Array based on the length of each string? Or what if you want to sort an Array whose elements aren't Equatable? Or maybe you have a list of objects that have an id property and you want to sort by id, or maybe you want to sort blog posts by date?

You can achieve this using Array's sort(by:):

var words = ["hello", "world", "this", "is", "a", "list", "of", "strings"]
words.sort(by: { lhs, rhs in
  return lhs.count < rhs.count
}) // words is ["a", "is", "of", "this", "list", "hello", "world", "strings"]
Enter fullscreen mode Exit fullscreen mode

You can use any kind of comparison logic in the closure that you pass to sort(by:). In this example, I used count which is a property of String to sort my Array by string length.

Note that sort() and sort(by:) both modify the source Array in-place. If you don't want to modify the source and create a new Array instead, you can use sorted() or sorted(by:).

let words = ["hello", "world", "this", "is", "a", "list", "of", "strings"]
let sorted = words.sorted(by: { lhs, rhs in
  return lhs.count < rhs.count
}) // sorted is ["a", "is", "of", "this", "list", "hello", "world", "strings"]
Enter fullscreen mode Exit fullscreen mode

If you have any questions about this tip, or if you have feedback for me, don't hesitate to send me a Tweet!

💖 💪 🙅 🚩
donnywals
Donny Wals

Posted on February 25, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related