Skip to content

Instantly share code, notes, and snippets.

@JoshBroomberg
Created May 23, 2017 19:00
Show Gist options
  • Save JoshBroomberg/3e957d09e1eaa3f482f2b7a25c2e28b9 to your computer and use it in GitHub Desktop.
Save JoshBroomberg/3e957d09e1eaa3f482f2b7a25c2e28b9 to your computer and use it in GitHub Desktop.
Swift: encode non-ascii characters as utf8 hex
import Foundation
extension Character {
var asciiValue: UInt32? {
return String(self).unicodeScalars.filter{$0.isASCII}.first?.value
}
}
func encodeNonASCIIAsUTF8Hex(toEncode: String) -> String{
var result = ""
for character in toEncode.characters {
if character.asciiValue != nil {
result.append(character)
} else {
for byte in String(character).utf8 {
result.append("\\x" + (NSString(format:"%2X", byte) as String))
}
}
}
return result
}
encodeNonASCIIAsUTF8Hex(toEncode: "Josh Broomberg’s iPhone")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment