The right way to compare strings in Swift


Greetings, traveler!

Today, we will talk about string comparison. There is a prominent method to do that. Check out this example:

let string1 = "Livsy Code"
let string2 = "Livsy Code"

string1 == string2 // true

However, in some cases, we must prioritize safety in our string comparisons. Consider this example:

struct User {
    let name: String
}

let user1 = User(name: "zoe")
let user2 = User(name: "Zoe")

user1.name == user2.name // false

So, we can write such a code:

user1.name.lowercased() == user2.name.lowercased() // true

The first issue is that the method lowercased() creates a copy of String every time it’s called. This will decrease your app’s performance a bit. But, sure thing, there is very little chance that this will drastically affect the user experience.

But what if we had come across something like this?

let user1 = User(name: "Zoe")
let user2 = User(name: "Zoë")

The lowercased() method is no more valid for this situation. Fortunately, Apple offers a convenient API for string comparison.

let result = user1.name.compare(user2.name)

let isEqual = result == .orderedSame // false

We can add some options to this method to handle all the possible cases. First, we need to make this method case-insensitive. Second, we need to make it diacritic-insensitive. To do this, we must add the .caseInsensitive and the .diacriticInsensitive options.

let result = user1.name.compare(user2.name, options: [.caseInsensitive, .diacriticInsensitive])

let isEqual = result == .orderedSame // true

Nice!

Conclusion

I never get tired of enjoying the convenience and elegance of Apple’s APIs.