【问题标题】:Encoding Swift string as escaped unicode?将 Swift 字符串编码为转义的 unicode?
【发布时间】:2020-06-16 10:09:59
【问题描述】:

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)

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 吗?这些格式是否没有跨语言标准化。

【问题讨论】:

  • 为什么不能直接将原始字符串发送到服务器? Unicode 本身就是“标准化格式”。
  • 这是AWS的一个约束:“用户定义的元数据是一组键值对。Amazon S3以小写形式存储用户定义的元数据键。每个键值对必须符合US-ASCII当您使用 REST 和 UTF-8 时,当您使用 SOAP 或通过 POST 进行基于浏览器的上传时。”他们不再使用 SOAP 客户端,我猜我可以自己编写。 docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html

标签: swift unicode


【解决方案1】:

您可以在集合中使用 reduce 并检查每个字符是否为 ASCII,如果为 true,则返回该字符,否则将特殊字符转换为 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 ? in the ?.
  And some new lines.
"""

let asciiRepresentation = textContainingUnicode.asciiRepresentation
print(asciiRepresentation)  // "Let's go \\U0001F3CA in the \\U0001F30A.\n  And some new lines."

【讨论】:

  • 如果你打算使用 Swift 5,你可以使用新的非转义字符串文字并去掉一些反斜杠
  • 感谢 Leo -- 很酷地完成了创建 utf-8 字符串的逻辑。我会接受这个答案,感谢您抽出宝贵的时间。
  • 不错!谢谢狮子座
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-09
  • 1970-01-01
相关资源
最近更新 更多