Last active
February 18, 2019 08:24
-
-
Save kmdarshan/36abd7d48f5175704f2a4e764130ac7c to your computer and use it in GitHub Desktop.
String comparison in Swift and Objective-C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Lets start by comparing the same string in Swift. | |
// Unicode defines U+00E9, Latin small letter e with acute, as a single value. | |
// But you can also write it as the plain letter e, followed by U+0301, combining acute accent. | |
// In both cases, what’s displayed is é, and a user probably has a reasonable expectation | |
// that two strings displayed as “résumé” would not only be equal to each other but also | |
// have a “length” of six characters, no matter which technique was used to produce the é in either one. | |
// They would be what the Unicode specification describes as canonically equivalent. | |
let single = "Pok\u{00E9}mon" | |
let double = "Poke\u{0301}mon" | |
if(single == double) | |
{ | |
print("They are equal") | |
} | |
// Lets try the same thing in Objective-C | |
let nssingle = single as NSString | |
nssingle.length // → 7 | |
let nsdouble = double as NSString | |
nsdouble.length // → 8 | |
if(nssingle == nsdouble) | |
{ | |
print("They are equal NS") | |
} | |
else | |
{ | |
print("they are not equal NS") // This will be printed. | |
// The strings will not be printed, because of the == operator implementation in objective-c | |
// Both the strings will be compared literally. So they will fail to match. | |
} | |
// This is how we fix it. Use compares to check the values of the strings. | |
if(nssingle.compare(String(nsdouble)) == ComparisonResult.orderedSame) | |
{ | |
print("They are equal") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment