Skip to content

Instantly share code, notes, and snippets.

@chuganzy
Last active March 23, 2016 04:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chuganzy/a1970d804cad6c980e47 to your computer and use it in GitHub Desktop.
Save chuganzy/a1970d804cad6c980e47 to your computer and use it in GitHub Desktop.
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