Apple Apple - 1 month ago 4x
iOS Question

How to store nested dictionary value

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 == 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 == 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]
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.


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 variable). This is much faster (O(1)).

You can shorten the whole snippet into one line:

let abilitiesArray = heroForDetails.hero.abilities[]!

Also, I don't see a question in your post...