快速排序具有多个排序条件的数组 [英] Swift Sort an array with multiple sort criteria

查看:241
本文介绍了快速排序具有多个排序条件的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift中如何通过多个条件对数组进行排序?例如,如下所示的字典数组:

How is an array sorted by multiple criteria in Swift? For example, an array of dictionaries as shown:

items = [
    [
        "item":"itemA"
        "status":"0"
        "category":"B"
    ],[
        "item":"itemB"
        "status":"1"
        "category":"C"
    ],[
        "item":"itemC"
        "status":"0"
        "category":"A"
    ],[
        "item":"itemD"
        "status":"2"
        "category":"A"
    ]
]

这需要进行如下排序:

  1. 类别ASC
  2. 状态DESC

我已经成功地基于 条件1或2对该数组进行了排序,但不是同时基于这两种条件.以下是该代码:

I have successfully sorted this array based on either condition 1 OR 2, but not both. Below is the code for that:

itemArray.sort({
        $0["category"] < $1["category"])
    })

如何将其扩展为以给定顺序包含多个排序条件?

How can this be expanded to include multiple sort criteria in a given order?

推荐答案

您要进行字典比较,即如果第一个字段相等,则比较第二个字段,否则比较第一个字段.

You want a lexicographic comparison i.e. if the first fields are equal, compare the second fields, otherwise compare the first fields.

由于您不想两次提取数据并且可能会丢失键,因此字典使它变得有些复杂,但这实际上很好,因为==<可以处理可选的比较.

The dictionary complicates it a bit since you don’t want to fetch the data out twice and keys may be missing, but that’s actually fine since == and < can handle optional comparisons.

let result = items.sorted {
    switch ($0["category"],$1["category"]) {
    // if neither "category" is nil and contents are equal,
    case let (lhs,rhs) where lhs == rhs:
        // compare "status" (> because DESC order)
        return $0["status"] > $1["status"]
    // else just compare "category" using <
    case let (lhs, rhs):
        return lhs < rhs
    }
}

实际上在某些情况下可以使用lexicographicCompare进行比较-但在这种情况下将不起作用,因为a)可选内容虽然可以与<进行比较,但不符合Comparable,因此您必须手动检查nil,并且b)您想按降序对第二个条目进行排序.

There’s actually a lexicographicCompare that you could use under some circumstances to do the comparison – but it won’t work in this case because a) optionals, while they can be compared with <, don’t conform to Comparable so you’d have to check for nils manually, and b) you want to sort the second entry in descending order.

这篇关于快速排序具有多个排序条件的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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