ios 在 Swift 中对 NSDictionary 对象的 NSArray 进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24685230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:19:26  来源:igfitidea点击:

Sort NSArray of NSDictionary objects in Swift

iosarrayssortingdictionaryswift

提问by jopeek

I have retrieved some JSON data from an API and now have an NSArray full of NSDictionary objects. Each NSDictionary has a key/value pair of "name" and I want to sort the NSArray by that key/value pair.

我已经从 API 中检索到了一些 JSON 数据,现在有了一个充满 NSDictionary 对象的 NSArray。每个 NSDictionary 都有一个“名称”键/值对,我想按该键/值对对 NSArray 进行排序。

I've done quite a bit of searching but none of the solutions I've come across seem to work in the new Swift language and I'm not sure if it's possibly a bug or not...

我已经做了很多搜索,但我遇到的所有解决方案似乎都不适用于新的 Swift 语言,我不确定它是否可能是一个错误......

I've tried:

我试过了:

var descriptor: NSSortDescriptor = NSSortDescriptor(key: "name", ascending: true)
var sortedResults: NSArray = results.sortedArrayUsingDescriptors(NSSortDescriptor(key: "name", ascending: true))

But that won't compile stating "NSSortDescriptor is not convertible to [AnyObject]".

但这不会编译说明“NSSortDescriptor 不可转换为 [AnyObject]”。

Any advice?

有什么建议吗?

回答by kambala

you must pass an array of sort descriptors (even if it's only one):

您必须传递一组排序描述符(即使它只有一个):

var descriptor: NSSortDescriptor = NSSortDescriptor(key: "name", ascending: true)
var sortedResults: NSArray = results.sortedArrayUsingDescriptors([descriptor])

回答by ColinE

Rather than doing this the old way, why not embrace the new? The swift Array type has both sortand sortedmethods. You can supply a closure as the sort function:

与其以旧方式这样做,为什么不拥抱新方式呢?swift Array 类型同时具有sortsorted方法。您可以提供一个闭包作为排序函数:

var sortedResults= results.sorted {
  (dictOne, dictTwo) -> Bool in 
  // put your comparison logic here
  return dictOne["name"]! > dictTwo["name"]!
}

回答by Ankit Goyal

var arrDescriptor = NSSortDescriptor(key: "", ascending: true)
   var sortDescriptors: NSArray = [arrDescriptor]
   _sortedArray = allKeysArray.sortedArrayUsingDescriptors(sortDescriptors as [AnyObject])

   print(_sortedArray)