Oliver Pinchbeck
Oliver Pinchbeck

Reputation: 11

Return a specific dictionary from an array of dictionaries in Swift

I'm getting an array of dictionaries back from an API that changes in order, and I'm trying to work out how to identify the element that I need.

If I knew which element I needed, I'd do it like this:

let DataDictionary = DataArray[0] as NSDictionary

But the issue is that the order of the array does not stay the same, so instead of accessing by index, I need to 1) search through the array, 2) return the dictionary with the matching key value pair. Such as: "if 'id = 98765' then return this dictionary" :

    for element in DataArray as Array<Dictionary<String,String>> {

        if element["id"] == "987654" {

        println("\(element)")
        }

    }

I don't think I can typecast in this way though, and I wouldn't be at all surprised if I'm making a ton of other mistakes as well...

If anyone can provide any guidance on this, that would be amazing. If my explanation is not detailed enough, I'll be happy to provide more details - this is my first Stack Overflow post!

All the best, oli

Upvotes: 1

Views: 1538

Answers (3)

Mahesh Kumar
Mahesh Kumar

Reputation: 1104

For swift 3.0 ("filteredArrayUsingPredicate(predicate)" ) updated as below:

let array = [
["id": "1", "theOne": "no"],
["id": "2", "theOne": "no"],
["id": "98765", "theOne": "yes"],
["id": "4", "theOne": "no"]
] 
let predicate = NSPredicate(format: "(id == '98765')")!
let theOne = (array as NSArray).filtered(using: predicate).first

Thanks

Upvotes: 1

Rengers
Rengers

Reputation: 15238

Looping works, as does the filter function, but this is what NSPredicates were made for:

let array = [
    ["id": "1", "theOne": "no"],
    ["id": "2", "theOne": "no"],
    ["id": "98765", "theOne": "yes"],
    ["id": "4", "theOne": "no"]
]

let predicate = NSPredicate(format: "(id == '98765')")!
let theOne = (array as NSArray).filteredArrayUsingPredicate(predicate).first

Edit

On second thought, filter is a little less verbose:

let theOne = array.filter { $0["id"] == "98765" }.first

Upvotes: 5

Javier Flores Font
Javier Flores Font

Reputation: 2093

I think this can work... haven't tested.

var dictionaryId: Int?
for dictionary in DataArray {
   if let dictionary as? NSDictionary {
      dictionaryId = dictionary["id"] as? Int
      if dictionaryId != nil && dictionaryId ==98765
      {
         return dictionary;
      }
   }
}
return nil;

Upvotes: 0

Related Questions