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

Milan Panchal
Mac O’Clock
Published in
2 min readFeb 6, 2021

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):

Lexical Sorting

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.

We can achieve natural sorting in swift using the localizedStandardCompare(_:) method from the Foundation framework.

Example 2 (Natural Sort):

Natural Sorting

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

We can also use the compare(_:options:) method to achieve the same result.

Summary:

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

Questions?

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

--

--

Milan Panchal
Mac O’Clock

iOS Team Lead ǁ Swift ǁ Objective-C ǁ Lifelong Learner ǁ Blogger — Join Medium from the following link: https://medium.com/@milanpanchal24/membership