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.
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)")
}
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)
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments