Last active
July 19, 2016 14:46
-
-
Save ivanbruel/2a91a7456236d42eb35d547205d232fa to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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