Bad practice: using .lowercased() to compare strings


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 🍿


Can you guess what’s wrong with this code?

We’re taking a searchQuery that the user has typed and we’re comparing it to a value from a database.

And since we want to make the search case insensitive, we make both strings .lowercased().

But while it’s a very good idea for the user experience to make the search case insensitive, this code is not the best way to implement it!

First because the method .lowercased() creates a new copy of each String every time it’s called, which might have a negative impact on performances.

But more importantly because to provide a great user experience, you actually need more than just a case insensitive search!

You probably also want to ignore all diacritics, like accents.

Fortunately, the type String comes with a built-in method that’s perfect for this job!

This method is called .compare() and it allows you to specify options for the comparison.

And among the supported options we can specify both .caseInsensitive and .diacriticInsensitive 👌

That’s all for this video, I hope you’ve enjoyed discovering this new API!

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

import Foundation

let searchQuery = "cafe"
let databaseValue = "Café"

let comparisonResult = searchQuery.compare(
    databaseValue,
    options: [.caseInsensitive, .diacriticInsensitive]
)

if comparisonResult == .orderedSame {
    // ...
}
Previous
Previous

How to write safer code using the Lock 🔒 and Key 🔑 pattern

Next
Next

Do you know what translatesAutoresizing MaskIntoConstraints actually does? 🤨