ylliX - Online Advertising Network
Wrapping async-await with a completion handler in Swift

Sorting arrays in Swift: multi-criteria


Swift’s foundation library provides a sorted(by:) function for sorting arrays. The areInIncreasingOrder closure needs to return true if the closure’s arguments are increasing, false otherwise. How to use the closure for sorting by multiple criteria? Let’s take a look at an example of sorting an array of Player structs.

  1. Sort by score in descending order
  2. Sort by name in ascending order
  3. Sort by id in ascending order


As said before, the closure should return true if the left element should be ordered before the right element. If they happen to be equal, we should use the next sorting criteria. For comparing strings, we’ll go for case-insensitive sorting using Foundation’s built-in localizedCaseInsensitiveCompare.


If this was helpful, please let me know on Mastodon@toomasvahter or Twitter @toomasvahter. Feel free to subscribe to RSS feed. Thank you for reading.





Source link

Leave a Reply

Your email address will not be published. Required fields are marked *