Comparing strings in Swift is not as simple as it may seem. Some of the aspects that you may want to consider when comparing strings:
"Apple"
and "apple"
are the same in a case-insensitive comparison, but different in a case-sensitive one."café"
and "cafe"
are the same in a diacritic-insensitive comparison, but different in a diacritic-sensitive one."ß"
and "ss"
are the same in German, but different in English."2"
and "02"
are the same in a numeric-sensitive comparison, but different in a numeric-insensitive one."A"
and "A"
are the same in a width-insensitive comparison, but different in a width-sensitive one.You should also test your code with different inputs and edge cases to ensure that your comparisons are accurate and consistent.
The simplest way to compare two strings is to use the ==
operator, which returns true
if the strings are exactly the same, and false
otherwise.
let a = "Hello"
let b = "Hello"
let c = "hello"
a == b // true
a == c // false
However, sometimes you may want to compare two strings without considering the case or the diacritic marks (such as accents or umlauts). In that case, you can use the compare(_:options:)
method, which takes a string and an option parameter, and returns a ComparisonResult
value.
let a = "café"
let b = "Cafe"
let c = "Café"
a.compare(b, options: .caseInsensitive) // .orderedSame
a.compare(c, options: .diacriticInsensitive) // .orderedSame
a.compare(b, options: [.caseInsensitive, .diacriticInsensitive]) // .orderedSame
The compare(_:options:)
method also allows you to specify other options, such as .numeric
, .widthInsensitive
, or .forcedOrdering
.
Alternatively, you can use the caseInsensitiveCompare(_:)
method, which is a shorthand for compare(_:options:)
with the .caseInsensitive
option.
let a = "a"
let b = "A"
a.caseInsensitiveCompare(b) // .orderedSame