Sort array on two parameters in swift

浪尽此生 提交于 2019-12-19 05:09:03

问题


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:


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]


来源:https://stackoverflow.com/questions/27193645/sort-array-on-two-parameters-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!