How do you compare strings in Swift?

← Swift answers

Use == for equality, caseInsensitiveCompare or localizedCaseInsensitiveCompare to ignore case, and localizedStandardCompare to sort strings the way users expect.

let a = "Café"
let b = "Cafe\u{301}"        // e + combining accent
 
a == b                        // true: Swift compares canonical equivalence
"apple" < "banana"            // true: lexicographic order
 
"Hello".caseInsensitiveCompare("hello") == .orderedSame     // true
"Straße".localizedCaseInsensitiveCompare("STRASSE")          // locale-aware
 
"file10" .localizedStandardCompare("file2")   // .orderedDescending, numbers sorted naturally
 
"swiftui".hasPrefix("swift")   // true
"swiftui".contains("ui")       // true (Foundation, or the standard library on newer Swift)

Plain == and < are exact and fast, which suits identifiers and keys. For text shown to users, use the localized comparisons so accents, case and digits sort as people expect.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required