【问题标题】:Sort a dictionary array when the key is given as the parameter当键作为参数给出时对字典数组进行排序
【发布时间】:2017-06-12 13:19:55
【问题描述】:

我正在 swift3 中的一个项目中工作,我有一个名为“details”的 NSArray,其中包含 NSDictionary 对象。我的要求是对这个 NSArray 进行排序,如果“键”作为参数传递(例如:- 姓名、姓氏、年龄)。我的 NSArray 如下所示。

(
 {name:"John";
  lastName :"bow";
  age: "26"; 
 },
 {
  name:"paul";
  lastName :"law";
  age: "19";
  }

)

我怎样才能做到这一点??

【问题讨论】:

  • 你需要对数组进行排序吗?
  • objective-c 还是 swift?你标记了两者。这听起来像是家庭作业
  • Swift 3 就可以了

标签: swift nsarray


【解决方案1】:

试试这个:

NSSortDescriptor * sortDescriptors = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; // change your key here
NSArray * arrSortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray * sortedArray = [yourArray sortedArrayUsingDescriptors:arrSortDescriptors];
NSLog(@"sortedArray %@",sortedArray);

【讨论】:

    【解决方案2】:

    使用sort:

    var dicts = [["name":"b"], ["name":"a"], ["name":"z"], ["name":"f"]]
    dicts.sort { $0["name"]! < $1["name"]! }
    print(dicts)
    

    打印[["name": "a"], ["name": "b"], ["name": "f"], ["name": "z"]]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-22
      • 2016-04-17
      • 2016-03-03
      • 1970-01-01
      • 1970-01-01
      • 2014-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多