Swift如何按字节值而不是按字母顺序对字典键排序? [英] Swift how to sort dict keys by byte value and not alphabetically?

查看:91
本文介绍了Swift如何按字节值而不是按字母顺序对字典键排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用for循环来创建由dict键和值组成的字符串. 不幸的是,Swift在Mac和Linux上的行为有所不同.

I'm using a for loop to create a string of a dicts keys and values. Unfortunately swift behaves differently on Mac and Linux.

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

我想按字节值而不是按字母顺序对密钥进行排序,小写参数应在大写字母之后列出.

I want to sort my keys by byte value, not alphabetically, lowercase parameters should be listed after uppercase ones.

因此,诸如"AWT"之类的密钥应该位于诸如"Ast"之类的密钥之前.

So a key like "AWT" should come before a key like "Ast".

推荐答案

在Apple平台上,Swift字符串比较是基于所谓的"Unicode规范化形式D"的Unicode标量值的字典比较,请参见 在Swift中如何进行字符串比较

On Apple platforms, Swift strings comparison is a lexicographical comparison of Unicode scalar values, based on the so-called "Unicode Normalization Form D", see How String Comparison happens in Swift or What does it mean that string and character comparisons in Swift are not locale-sensitive? for details.

在Linux上,排序顺序不同.那是一个已知的问题 ( [String]排序顺序在Darwin与Linux上有所不同),应在以下位置进行修复雨燕4.

On Linux, the sort order is different. That is a known problem ([String] sort order varies on Darwin vs. Linux) and should be fixed in Swift 4.

如果您只关心ASCII字符,则可能的方法是 是比较字符串的UTF-8表示形式:

If you only care about ASCII characters then a possible approach would be to compare the UTF-8 representation of the strings:

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上提供了相同的结果.

This gives identical results on Apple platforms and on Linux.

但是请注意,这不是Swift字符串的默认排序顺序 在Apple平台上.要在Linux上复制该代码(在Swift 4中已修复),请执行以下操作 算法会起作用:

But note that this is not the default sort order for Swift Strings on Apple platforms. To replicate that on Linux (before it is fixed in Swift 4), the following algorithm would work:

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"]

这篇关于Swift如何按字节值而不是按字母顺序对字典键排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆