Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.