将 Swift 字符串编码为转义的 unicode?

tgk*_*tgk 5 unicode swift

API数据字段仅支持ASCII编码——但我需要支持Unicode(表情符号、外来字符等)

我想将用户的文本输入编码为转义的 unicode 字符串:

let textContainingUnicode = """
Let's go  in the .
  And some new lines.
"""

let result = textContainingUnicode.unicodeScalars.map { $0.escaped(asASCII: true)}
  .joined(separator: "")
  .replacingOccurrences(
    of: "\\\\u\\{(.+?(?=\\}))\\}", <- converting swift format \\u{****}
    with: "\\\\U$1",               <- into format python expects
    options: .regularExpression)
Run Code Online (Sandbox Code Playgroud)

result这是"Let\'s go \U0001F3CA in the \U0001F30A.\n And some new lines."

在服务器上用 python 解码:

codecs.decode("Let\\'s go \\U0001F3CA in the \\U0001F30A.\\n And some new lines.\n", 'unicode_escape')

但这听起来很有趣——我真的需要在 swift 中做这么多字符串操作才能获得转义的 unicode 吗?这些格式是否没有跨语言标准化?

Leo*_*bus 5

您可以在集合中使用reduce并检查每个字符是否为ASCII,如果为true则返回该字符,否则将特殊字符转换为unicode:

\n\n

斯威夫特 5.1 \xe2\x80\xa2 Xcode 11

\n\n
extension Unicode.Scalar {\n    var hexa: String { .init(value, radix: 16, uppercase: true) }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n
extension Character {\n    var hexaValues: [String] {\n        unicodeScalars\n            .map(\\.hexa)\n            .map { #"\\\\U"# + repeatElement("0", count: 8-$0.count) + $0 }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n
extension StringProtocol where Self: RangeReplaceableCollection {\n    var asciiRepresentation: String { map { $0.isASCII ? .init($0) : $0.hexaValues.joined() }.joined() }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n
let textContainingUnicode = """\nLet\'s go  in the .\n  And some new lines.\n"""\n\nlet asciiRepresentation = textContainingUnicode.asciiRepresentation\nprint(asciiRepresentation)  // "Let\'s go \\\\U0001F3CA in the \\\\U0001F30A.\\n  And some new lines."\n
Run Code Online (Sandbox Code Playgroud)\n