按键名搜索词典数组

时间:2016-04-21 07:30:20

标签: ios arrays swift dictionary search

我有一个字典数组,我需要搜索并返回匹配的Dict

let foo = [
    ["selectedSegment":0, "severity":3, "dataDictKey": "critical"],
    ["selectedSegment":1, "severity":2, "dataDictKey": "major"],
    ["selectedSegment":2, "severity":1, "dataDictKey": "minor"],
]

foo中,我如何找到severity:2并获得匹配的Dict?

3 个答案:

答案 0 :(得分:8)

使用filter功能

let foo = [
  ["selectedSegment":0, "severity":3, "dataDictKey": "critical"],
  ["selectedSegment":1, "severity":2, "dataDictKey": "major"],
  ["selectedSegment":2, "severity":1, "dataDictKey": "minor"],
]

let filteredArray = foo.filter{$0["severity"]! == 2}
print(filteredArray.first ?? "Item not found")

indexOf

if let filteredArrayIndex = foo.indexOf({$0["severity"]! == 2}) {
  print(foo[filteredArrayIndex])
} else {
  print("Item not found")
}

NSPredicate

let predicate = NSPredicate(format: "severity == 2")
let filteredArray = (foo as NSArray).filteredArrayUsingPredicate(predicate)
print(filteredArray.first ?? "Item not found")

Swift 3更新:

  • indexOf(已重命名为index(where:
  • filteredArrayUsingPredicate(predicate)已重命名为filtered(using: predicate)

答案 1 :(得分:1)

if let index = foo.flatMap({ $0["severity"] }).indexOf(2) {
    print(foo[index])
}

另一种方法。

第一个示例仅在用户100%确定所有词典都包含"severity"作为键时才有效。为了更安全:

if let index = foo.indexOf({ ($0["severity"] ?? 0) == 2 }) {
    print(foo[index])
}

答案 2 :(得分:-1)

如果您使用swift 3.1 -

 let  resultPredicate : NSPredicate = NSPredicate.init(format: "<your Key> CONTAINS [cd] %@", <value which you want to search>)
 let filteredArray = requstData.arrayForColl?.filter { resultPredicate.evaluate(with: $0) };