How to implement natural sorting on the alphanumeric array in swift?

How to implement natural sorting on the alphanumeric array in swift?

Sorting an array with strings and numbers in Swift

In Swift (or most of the programming language), the default method for sorting an array uses lexicographic order. That means string Foo12 does come before the string Foo2.

Example 1 (Lexical Sort):

image.png

In most cases, we perform lexical sorting on our array. But there might be a scenario where we need to use natural sorting for a better look on for end-user. (eg. Sorting File Names). In the natural soring order, the string Foo12 comes after the string Foo2.

Example 2 (Natural Sort):

image.png

The macOS Finder also uses localizedStandardCompare:, a method to sorts filenames.

image.png

Summary:

localizedStandardCompare(_:) method should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate.

You can find me on:

Twitter | Tooter | LinkedIn | GitHub | Medium | HackerRank | LeetCode | Stack Overflow

Did you find this article valuable?

Support Milan Panchal by becoming a sponsor. Any amount is appreciated!