I want to sort an array on two parameters, for example, name and then by description. Sorting the array first by name and then by description won't work because then the array won't be sorted by name.
我想在两个参数上对数组进行排序,例如,名称,然后是描述。首先按名称排序数组然后按描述排序将不起作用,因为这样数组将不按名称排序。
The solution should be something like this:
解决方案应该是这样的:
var sortedArray = sorted(items, { (o1: MyObject, o2: MyObject) -> Bool in
return o1.name < o2.name and o1.description < o2.description
})
Thanks
谢谢
1 个解决方案
#1
27
Your syntax looks correct. Just change the closure to
您的语法看起来正确。只需将闭包更改为
return o1.name == o2.name ? (o1.description < o2.description) : (o1.name < o2.name)
If you want more than two sort criteria I recommend using the old fashioned sort descriptors.
如果您想要两个以上的排序标准,我建议使用旧式排序描述符。
let sortedArray = (unsortedArray as NSArray).sortedArrayUsingDescriptors([
NSSortDescriptor(key: "name", ascending: true),
NSSortDescriptor(key: "description", ascending: true),
....
]) as! [Object]
#1
27
Your syntax looks correct. Just change the closure to
您的语法看起来正确。只需将闭包更改为
return o1.name == o2.name ? (o1.description < o2.description) : (o1.name < o2.name)
If you want more than two sort criteria I recommend using the old fashioned sort descriptors.
如果您想要两个以上的排序标准,我建议使用旧式排序描述符。
let sortedArray = (unsortedArray as NSArray).sortedArrayUsingDescriptors([
NSSortDescriptor(key: "name", ascending: true),
NSSortDescriptor(key: "description", ascending: true),
....
]) as! [Object]