Last active
March 23, 2016 04:15
-
-
Save chuganzy/a1970d804cad6c980e47 to your computer and use it in GitHub Desktop.
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
import Foundation | |
extension NSString { | |
func utf16IndexForIndex(index: Int) -> Int { | |
var index = index | |
var result = 0 | |
while result < index { | |
if result + 1 < self.length && | |
CFStringIsSurrogateHighCharacter(self.characterAtIndex(result)) && | |
CFStringIsSurrogateLowCharacter(self.characterAtIndex(result + 1)) { | |
index += 1 | |
} | |
result += 1 | |
} | |
return result | |
} | |
func indexForUTF16Index(index: Int) -> Int { | |
var result = index | |
(0..<min(self.length, index)).forEach { i in | |
if i + 1 < self.length && | |
CFStringIsSurrogateHighCharacter(self.characterAtIndex(i)) && | |
CFStringIsSurrogateLowCharacter(self.characterAtIndex(i + 1)) { | |
result -= 1 | |
} | |
} | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment