String isEqual case-insensitive?

I believe there should be an easier way than .lowercase() to compare 2 Strings without caring about the case.

Unless I missed something, we don't have isEqualToString: in Foundation with an option for the case.

The best String could have would be an operator like ~=, but at least a method (.e.g. isEqual(caseSensitive: Bool). That one reads very long and the true version barely makes any use case.

2 Likes

I was also thinking that hasPrefix and hasSuffix seriously could have an optional parameter (by default true) called caseSensitive.

Technically any of the 2 could be then used to compare 2 strings.

But I still prefer the idea of an operator like stringA ~= stringB.

import Foundation

let x = "HELLO WORLD", y = "hello world"
x.caseInsensitiveCompare(y) == .orderedSame // true

See link for description and related links.

1 Like

Okay, that's one option that I didn't know.

Maybe you are my opinion though that this doesn't read awesome.

Also, I was wondering if the ~= operator is used in Swift. I recall it's used in some other languages.

It's the pattern matching operator. See here.

1 Like

Ugh. Sure. I totally forgot about that because I had not done anything like that for years!

I guess I'm looking at another operator than ;-) ;-) =~? ;-)

Maybe you are my opinion though that this doesn't read awesome.

Fair ’nuff.

As you contemplate improving that, keep in mind that case-insensitive comparisons only really make sense in the context of a locale. Consider:

import Foundation

let s = "I"
let sEN = s.lowercased(with: Locale(identifier: "en_AU"))
let sTR = s.lowercased(with: Locale(identifier: "tr_TR"))
print(sEN)  // prints: i
print(sTR)  // prints: ı

The character in the second example is U+0131 LATIN SMALL LETTER DOTLESS I. If you search the ’net for turkish lowercase bug you’ll find an explanation of what’s going on here.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

5 Likes

Good catch. For user strings localizedCaseInsensitiveCompare should be used instead of caseInsensitiveCompare.