Encoding Swift string as escaped unicode?

后端 未结 1 978
粉色の甜心
粉色の甜心 2021-01-14 03:16

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

相关标签:
1条回答
  • 2021-01-14 04:07

    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                                                                     
    0 讨论(0)
提交回复
热议问题