Reputation: 123
I want to store the value of a nested dictionary so my collection view can use it later without having to loop through stuff to find it every time. I also don't think it'll work (i could be wrong tho) if i try to put the loop in my cellforindexatpath function. The "let abilitiesArray: [Ability] =....." is inside my class
Ultimately I want abilitiesArray = abilities. "heroForDetails.hero.abilities" is a [String: [Ability]] so I want to return the [Ability] whose heroForDetails.hero.id == heroId because there are multiple key: value pairs in heroForDetails.hero.abilities. The current error is missing return in closure expected to return [Ability].
let abilitiesArray: [Ability] = { () -> ([Ability]) in
let val = heroForDetails.hero.abilities
for (heroId, abilities) in val {
if heroForDetails.hero.id == heroId {
return abilities
}
}
}()
"abilities" is an array that I plan to use like so
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("AbilitiesCell", forIndexPath: indexPath) as? AbilitiesCell {
let ability: Ability
ability = abilitiesArray[indexPath.row]
cell.configureCell(ability)
return cell
}else {
return UICollectionViewCell()
}
}
I hope i did a good job at explaining this. I just started learning to code so Any help would be great. I could be going about this completely wrong too.
Upvotes: 1
Views: 55
Reputation: 824
You can access the dictionary by
let val = heroForDetails.hero.abilities
let abilities = val[heroForDeails.hero.id]
As far as accessing it in your cellforindexatpath, it should be just fine. Don't worry about the closure.
Upvotes: 0
Reputation: 272555
In your first code snippet, you seem to be finding an item in the val
dictionary using a key. I hope that's what you want to do. To do that, you don't need to loop through the whole dictionary. It's very slow to do so. (O(n)) You can use the subscript to access the dictionary using a key (the heroForDeails.hero.id
variable). This is much faster (O(1)).
You can shorten the whole snippet into one line:
let abilitiesArray = heroForDetails.hero.abilities[heroForDetails.hero.id]!
Also, I don't see a question in your post...
Upvotes: 1