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.
==
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
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
.
When working with text that’s presented to the user, use the localizedStandardCompare(_:)
instead, or use the compare(_:options:range:locale:)
method, passing the user’s locale.
caseInsensitiveCompare(_:)
method, which is an instance method belonging to the String
class. You call it on a string object to compare it with another string.let a = "a"
let b = "A"
a.caseInsensitiveCompare(b) // .orderedSame
It works similar to compare(_:options:)
with the .caseInsensitive
option as both performs a case-insensitive comparison of two strings.
You can also use localizedCaseInsensitiveCompare(_:)
if you need to compare two strings in a way that is case-insensitive and respects the current locale settings.