The API data field only supports ASCII encoding -- but I need to support Unicode (emoji, foreign characters, etc.)
I\'d like to encode the user\'s text input as an e
You can use reduce in your collection and check if each character isASCII, if true return that character otherwise convert the special character to unicode:
Swift 5.1 • Xcode 11
extension Unicode.Scalar {
var hexa: String { .init(value, radix: 16, uppercase: true) }
}
extension Character {
var hexaValues: [String] {
unicodeScalars
.map(\.hexa)
.map { #"\\U"# + repeatElement("0", count: 8-$0.count) + $0 }
}
}
extension StringProtocol where Self: RangeReplaceableCollection {
var asciiRepresentation: String { map { $0.isASCII ? .init($0) : $0.hexaValues.joined() }.joined() }
}
let textContainingUnicode = """
Let's go