Reputation: 2998
I have a view controller which has a textField on it. When a user presses the textField, it segues to a tableView and populates the tableView with the "name"
from my dictionary.
My dictionary data is as below:
var objects = [
{
"id": "001",
"typeTwo": "Poison",
"name": "Bulbasaur",
"type": "Grass"
},
{
"id": "002",
"typeTwo": "Poison",
"name": "Ivysaur",
"type": "Grass"
}]
... and so on.
When the user selects a cell, it passes the name back to the first VC and shows the pokemon image for what they selected.
This all works fine.
The user can then press a button which segues to a CollectionViewController
and you can see all the Pokemon shown.
What I'd like to then do:
Currently, I just have the CollectionView set up to just display all the Pokemon using the same dictionary data above, but What I'd like, is for it to only show the Pokemon that have the same "Type"
For example:
If the user selected "Bulbasaur"
, which has types of Grass and Poison, then when they go to the CollectionView, it would only show the Pokemon that are either Grass or Poison as well.
Hopefully, that makes sense, please let me know if you need to see any of my code.
Upvotes: 0
Views: 1760
Reputation: 1057
You can use filtering to filter dictionary to return only elements that match criteria you write in predicate which here is getting pokemons having a specific type :
var objects = [
[
"id": "001",
"typeTwo": "Poison",
"name": "Bulbasaur",
"type": "Grass"
],
[
"id": "002",
"typeTwo": "Fly",
"name": "Ivysaur",
"type": "Grass"
],
[
"id": "003",
"typeTwo": "Poison",
"name": "Ivysaur",
"type": "Water"
]
]
var filteredObjects = objects.filter{
let valueType = $0["type"]
let valueTypeTwo = $0["typeTwo"]
if (valueType == "Grass" || valueType == "Water") && valueTypeTwo == "Poison"
{
return true
}
return false
}
print(filteredObjects)
Upvotes: 1
Reputation: 131426
You should not use a dictionary as the model for a collection view. Dictionaries are unordered collections, and collection views show ordered lists of objects.
The data structure you've shown is an array of dictionaries. That's a perfectly valid way to store the data for a collection view since an array is an ordered collection.
Mohamed's code to filter your dictionary is a good way to filter your results, but you then need to use that new filtered array as the model (data) for your collection view.
Upvotes: 0