【问题标题】:Swift how to sort dict keys by byte value and not alphabetically?Swift 如何按字节值而不是按字母顺序对字典键进行排序?
【发布时间】:2017-10-10 19:37:32
【问题描述】:

我正在使用一个 for 循环来创建一个 dicts 键和值的字符串。 不幸的是,swift 在 Mac 和 Linux 上的行为不同。

for key in parameters.keys.sorted() {...}

我想按字节值排序我的键,而不是按字母顺序,小写参数应该列在大写参数之后。

所以像“AWT”这样的键应该在像“Ast”这样的键之前。

【问题讨论】:

  • 在 Apple 平台上,您将获得所需的订单。在 Linux 上,这是一个应该在 Swift 4 中修复的已知错误,请参阅bugs.swift.org/browse/SR-530。 – 注意这里跟字典或者key没有关系,只是字符串的比较是怎么实现的,print(["AWT", "Ast"].sorted())足以看出苹果和Linux的区别。
  • .sorted() 可以接受参数“使用给定谓词排序作为元素之间的比较”。有没有办法手动实现正确的排序?
  • 也许您应该首先澄清“按字节值排序”对您的确切含义。
  • 好吧,对我来说,这意味着当查找时:asciitable.com 所以大写“W”的十进制值位于小写“a”之前。所以就像在 ascii 表中一样,我想对其进行排序。与我的示例相比,“AWT”和“Ast”都以“A”开头,但随后“W”出现在“a”之前。
  • 非ASCII字符呢?在 Apple 平台上,“a”

标签: swift linux macos dictionary swift3


【解决方案1】:

在 Apple 平台上,Swift 字符串比较是 Unicode 标量值的字典比较,基于所谓的“Unicode Normalization Form D”,请参阅 How String Comparison happens in SwiftWhat does it mean that string and character comparisons in Swift are not locale-sensitive? 了解详情。

在 Linux 上,排序顺序不同。这是一个已知问题 ([String] sort order varies on Darwin vs. Linux) 并且应该在 Swift 4 中修复。

如果您只关心 ASCII 字符,那么一种可能的方法是 是比较字符串的UTF-8表示:

func utf8StringCompare(s1: String, s2: String) -> Bool {
    let u1 = s1.utf8
    let u2 = s2.utf8
    for (x, y) in zip(u1, u2) {
        if x < y { return true }
        if x > y { return false }
    }
    return u1.count < u2.count
}


let s = ["AWT", "Ast"].sorted(by: utf8StringCompare)
print(s) // ["AWT", "Ast"]

这在 Apple 平台和 Linux 上给出了相同的结果。

但请注意,这 不是 Swift 字符串的默认排序顺序 在苹果平台上。要在 Linux 上复制它(在 Swift 4 中修复它之前),以下 算法会起作用:

func unicodeStringCompare(s1: String, s2: String) -> Bool {
    let u1 = s1.decomposedStringWithCanonicalMapping.unicodeScalars
    let u2 = s2.decomposedStringWithCanonicalMapping.unicodeScalars
    for (x, y) in zip(u1, u2) {
        if x.value < y.value { return true }
        if x.value > y.value { return false }
    }
    return u1.count < u2.count
}

let someStrings = ["a", "b", "e", "f", "ä", "é"].sorted(by: unicodeStringCompare)
print(someStrings) // ["a", "ä", "b", "e", "é", "f"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 2014-01-26
    • 2015-04-06
    • 2013-04-03
    • 2018-01-27
    相关资源
    最近更新 更多