如何按多个值对结构数组排序? [英] How do I sort an array of structs by multiple values?

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

问题描述

我已经有代码可以按1个值进行排序,如下所示,但是我想知道如何使用多个值进行排序?我想按集合排序,然后按someString排序.

I already have code to sort by 1 value as shown below, but I'm wondering how to sort using multiple values? I would like to sort by set and then by someString.

在这种情况下,一个是整数,一个是字符串.我曾考虑过将整数转换为字符串,然后将它们连接起来,但是我认为必须有更好的方法,因为将来我可能会使用2个整数进行排序.

One is an integer, and one is a string in this case. I had considered converting the integer to a string and then concatenating them, but thought there must be a better way because I may have 2 integers to sort by in the future.

struct Condition {
    var set = 0
    var someString = ""
}

var conditions = [Condition]()

conditions.append(Condition(set: 1, someString: "string3"))
conditions.append(Condition(set: 2, someString: "string2"))
conditions.append(Condition(set: 3, someString: "string7"))
conditions.append(Condition(set: 1, someString: "string9"))
conditions.append(Condition(set: 2, someString: "string4"))
conditions.append(Condition(set: 3, someString: "string0"))
conditions.append(Condition(set: 1, someString: "string1"))
conditions.append(Condition(set: 2, someString: "string6"))

// sort
let sorted = conditions.sorted { (lhs: Condition, rhs: Condition) -> Bool in
    return (lhs.set) < (rhs.set)
}

// printed sorted conditions
for index in 0...conditions.count-1 {
    println("\(sorted[index].set) - \(sorted[index].someString)")
}

推荐答案

我还不精通Swift,但是多标准排序的基本思想是:

I'm not yet proficient in Swift, but the basic idea for a multiple-criteria sort is:

let sorted = conditions.sorted { (lhs: Condition, rhs: Condition) -> Bool in
    if lhs.set == rhs.set {
        return lhs.someString < rhs.someString
    }
    return (lhs.set) < (rhs.set)
}

这篇关于如何按多个值对结构数组排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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