Ios 如何存储嵌套字典值

Ios 如何存储嵌套字典值,ios,arrays,swift,dictionary,nested,Ios,Arrays,Swift,Dictionary,Nested,我想存储嵌套字典的值,这样我的集合视图就可以在以后使用它,而不必每次都循环查找它。我也不认为如果我尝试在CellForIndexatePath函数中加入循环会起作用(我可能是错的)。“让能力排列:[能力]=…”在我的课堂上 最终我想要的是能力阵列=能力。“herofDetails.hero.abilities”是一个[String:[Ability]],因此我想返回其herofDetails.hero.id==heroId的[Ability],因为herofDetails.hero.abilit

我想存储嵌套字典的值,这样我的集合视图就可以在以后使用它,而不必每次都循环查找它。我也不认为如果我尝试在CellForIndexatePath函数中加入循环会起作用(我可能是错的)。“让能力排列:[能力]=…”在我的课堂上

最终我想要的是能力阵列=能力。“herofDetails.hero.abilities”是一个[String:[Ability]],因此我想返回其herofDetails.hero.id==heroId的[Ability],因为herofDetails.hero.abilities中有多个键:值对。当前错误在预期返回[能力]的闭包中缺少返回

let abilitiesArray: [Ability] = { () -> ([Ability]) in
    let val = heroForDetails.hero.abilities
    for (heroId, abilities) in val {

        if heroForDetails.hero.id == heroId {
            return abilities
        }
    }
}()
“能力”是我计划像这样使用的数组

   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()
    }
}

我希望我能很好地解释这一点。我刚开始学习编码,所以任何帮助都会很好。这一点我可能也完全错了。

你可以通过

let val=herofordails.hero.abilities
让能力=val[heroForDeails.hero.id]


至于在CellForIndexathPath中访问它,应该还可以。不要担心闭包。

在您的第一个代码片段中,您似乎正在使用键在
val
字典中找到一项。我希望这就是你想做的。要做到这一点,您不需要遍历整个词典。这样做很慢。(O(n))您可以使用下标使用键(herofordails.hero.id变量)访问字典。这要快得多(O(1))

您可以将整个代码段缩短为一行:

let abilitiesArray = heroForDetails.hero.abilities[heroForDetails.hero.id]!

另外,我在你的帖子中没有看到任何问题…

因为没有看到一个问题,你回答得很好。这正是我所需要的,而且它现在起作用了。谢谢(问题在标题中)