Discover localizedStandardCompare()


You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿


Have you ever heard of a function called localizedStandardCompare()?

Imagine that you have an array of file names, and that you want to order them:

The straightforward approach would be to call the method sorted() on the array:

Because String conforms to the protocol Comparable, you don’t even need to explicitly provide a comparison function.

However, when you look at the result, it probably won’t be what you were expecting!

You would probably expect the file names to be ordered by ascending numbering, like the Finder app would do.

But this is not what happens. And it’s definitely not a bug!

It’s because when you compare the Strings character by character, 1 does come before 2 and 2 does come before 5:

In order to have a Finder-like ordering, we need a comparison function that takes into account whether a digit represents a unit, a ten or a hundred.

And this is exactly what localizedStandardCompare() will achieve!

This function uses the current Locale in order to sort an array of strings in the same way the Finder app would.

And the usefulness of this function doesn’t limit to numberings, it can also be very helpful when dealing with diacritics, like accents, or even people’s name 👌

That’s all for this article, I hope you’ve enjoyed it!

Here’s the code if you want to experiment with it:

import Foundation

let fileNames = [
    "File 100.txt",
    "File 5.txt",
    "File 20.txt"
]

// ["File 5.txt", "File 20.txt", "File 100.txt”]
fileNames.sorted {
    $0.localizedStandardCompare($1) == .orderedAscending
}
Previous
Previous

I can teach you SwiftUI in 12 hours 👩🏼‍🎓👨🏻‍🎓

Next
Next

How risky is it to use [unowned self]? 🤔