Mike Henderson
Mike Henderson

Reputation: 2142

Case-insensitve string comparison

Is there any difference between the following ways of comparing strings without case in Swift?

let equal = str1.lowercased() == str2.lowercased() // or uppercased()

vs:

let equal = str1.caseInsensitiveCompare(str2) == .orderedSame

Is there any case in any language where one returns an incorrect result? I'm more interested in Unicode correctness than performance.

Upvotes: 1

Views: 193

Answers (2)

Rob
Rob

Reputation: 438487

The caseInsensitiveCompare can be far more efficient (though I'd be shocked if it's observable in normal every day usage). And, IMHO, it's more intuitive regarding the intent.

Regarding "unicode correctness", I guess it depends upon what you mean. For example, comparing "Straße" to "strasse", caseInsensitiveCompare will say they're the same, whereas lowercased approach will not (though uppercased will).

But if you compare "\u{E9}" to "\u{65}\u{301}" in Swift 4 (see the unicode correctness discussion in WWDC 2017 What's New in Swift), they both correctly recognize that those are é and will say they're the same, even though those two strings have different numbers of unicode scalars.

Upvotes: 1

Sandip Mane
Sandip Mane

Reputation: 1633

Both do the same thing, lowercased() or uppercased() won't affect the Unicode characters so the end result will always be matching to other string when you compare.

These methods support all types of special characters including emoji icons.

Same goes with caseInsensitiveCompare; this too will ignore special characters, symbols etc.

Upvotes: 0

Related Questions