How to implement natural sorting on the alphanumeric array 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
Example 1 (Lexical Sort):
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
We can achieve natural sorting in swift using the
localizedStandardCompare(_:) method from the
Example 2 (Natural Sort):
The macOS Finder also use
localizedStandardCompare:, method tosorts filenames.
We can also use the
compare(_:options:) method to achieve the same result.
localizedStandardCompare(_:) method should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate.
Please feel free to comment below, if you have any questions.
If you like this article, feel free to share it with your friends and leave me a comment. Also, click on the 👏 clap button below to show how much you like the article.
Thanks for reading! 👨🏼💻
You can find me on:
Twitter | LinkedIn | GitHub | Medium | HackerRank | LeetCode | Stack Overflow