我已经有按1个值排序的代码,如下所示,但是我想知道如何使用多个值进行排序?我想按集合排序,然后按someString排序。
在这种情况下,一个是整数,一个是字符串。我曾考虑过将整数转换为字符串,然后将它们连接起来,但是我认为必须有更好的方法,因为将来我可能会有2个整数进行排序。
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,但是多标准排序的基本思想是:
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) }