Skip to content

Instantly share code, notes, and snippets.

@ivanbruel
Last active July 19, 2016 14:46
Show Gist options
  • Save ivanbruel/2a91a7456236d42eb35d547205d232fa to your computer and use it in GitHub Desktop.
Save ivanbruel/2a91a7456236d42eb35d547205d232fa to your computer and use it in GitHub Desktop.
extension String {
init?(utf16chars:[UInt16]) {
var str = ""
var generator = utf16chars.generate()
var utf16 : UTF16 = UTF16()
var done = false
while !done {
let result = utf16.decode(&generator)
switch result {
case .EmptyInput:
done = true
case let .Result(val):
str.append(Character(val))
case .Error:
return nil
}
}
self = str
}
func escapeUTF16() -> String {
return Array(utf16)
.map { String(format: "%04x", $0) }
.reduce("") { (string, character) -> String in
return "\(string)\(character)"
}
}
func unescapeUTF16() -> String? {
var index = 0
var encodedChars = [UInt16]()
while index < characters.count {
let range = startIndex.advancedBy(index)..<startIndex.advancedBy(index + 4)
let encodedChar = String(substringWithRange(range))
let intValue = UInt16(strtoul(encodedChar, nil, 16))
encodedChars.append(intValue)
index += 4
}
return String(utf16chars: encodedChars)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment