swift 使用字母表和快速计数进行多重排序

9jyewag0  于 2023-01-12  发布在  Swift
关注(0)|答案(2)|浏览(155)

我不得不对数组进行多重排序,但它不起作用
这是预期输出。现在此数组混淆了

struct Variant {
    var name: String
    var count: Int
}

let array = [
    Variant(name: "Ab", count: 12),
    Variant(name: "Ac", count: 10),
    Variant(name: "Ad", count: 8),
    Variant(name: "Ae", count: 0)
    Variant(name: "Bc", count: 55),
    Variant(name: "Bd", count: 45)]

我试着这样做,但它使计数优先,并不关心名称

array = array.sorted(by: {
    ($0.count ?? 0, $1.name) > ($1.count ?? 0, $0.name)
})
blmhpbnm

blmhpbnm1#

元组比较是按多个标准对元素进行排序的好方法,但是您弄错了元组元素的顺序。
元组以“字典顺序”进行比较,从第一个(最左边)元素开始。为了首先按名称排序,$0.name$1.name必须是第一个元组元素。
因此,首先按名称(升序)排序,然后按计数(降序)排序,排序函数应为

array.sorted(by: {
    ($0.name, $1.count) < ($1.name, $0.count)
})
kq4fsx7k

kq4fsx7k2#

要基于多个条件进行排序,只需包含基于优先级相互级联的条件。
编辑:感谢Martin R指出错误,以下是修改后的代码:

array.sorted(by: {
    //First layer of filter. Sorts based on alphabetic order
    if $0.name < $1.name {
        return true
    }
    else if $0.name > $1.name {
        return false
    }
    //Second layer. Sorts based on greater count
    return $0.count > $1.count
})

输入:

let array = [
    Variant(name: "Bd", count: 55),
    Variant(name: "Bc", count: 55),
    Variant(name: "Ac", count: 12),
    Variant(name: "Ab", count: 12),
    Variant(name: "Ad", count: 8),
    ]

排序后:

Variant(name: "Ab", count: 12),
Variant(name: "Ac", count: 12),
Variant(name: "Ad", count: 8),
Variant(name: "Bc", count: 55), 
Variant(name: "Bd", count: 55)

相关问题