DEV Community

Donny Wals
Donny Wals

Posted on • Originally published at donnywals.com

4 1

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!

Sentry mobile image

Mobile Vitals: A first step to Faster Apps

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read the guide

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay