steve steve - 5 months ago 25
Swift Question

Search in Array of Dictionaries by key name

I have an array of dictionary, in which i need to search and return matching Dict

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


In
foo
, how can i find for
severity:2
and get matching Dict ?

Answer

Use the filter function

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")

or indexOf

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

or NSPredicate

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

Swift 3 Update:

  • indexOf( has been renamed to index(where:
  • filteredArrayUsingPredicate(predicate) has been renamed to filtered(using: predicate)