Created
May 23, 2017 19:00
-
-
Save JoshBroomberg/3e957d09e1eaa3f482f2b7a25c2e28b9 to your computer and use it in GitHub Desktop.
Swift: encode non-ascii characters as utf8 hex
This file contains 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
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