【问题标题】:How to store nested dictionary value如何存储嵌套字典值
【发布时间】:2017-01-19 04:29:11
【问题描述】:

我想存储嵌套字典的值,以便我的集合视图可以在以后使用它,而不必每次都循环查找它。如果我尝试将循环放在我的 cellforindexatpath 函数中,我也不认为它会起作用(我可能是错的)。 “letabilitiesArray: [Ability] =.....”在我的班级里

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

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

        if heroForDetails.hero.id == heroId {
            return abilities
        }
    }
}()

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

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

【问题讨论】:

    标签: ios arrays swift dictionary nested


    【解决方案1】:

    您可以通过

    访问字典

    let val = heroForDetails.hero.abilities let abilities = val[heroForDeails.hero.id]

    就在您的 cellforindexatpath 中访问它而言,应该没问题。不用担心关闭。

    【讨论】:

      【解决方案2】:

      在您的第一个代码 sn-p 中,您似乎正在使用一个键在 val 字典中查找一个项目。我希望这就是你想要做的。为此,您无需遍历整个字典。这样做非常缓慢。 (O(n)) 您可以使用下标通过键(heroForDeails.hero.id 变量)访问字典。这要快得多 (O(1))。

      您可以将整个 sn-p 缩短为一行:

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

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

      【讨论】:

      • 因为没有看到您设法回答的问题。这就是我所需要的,它现在可以工作了。谢谢! (问题在标题中)
      猜你喜欢
      • 2019-07-16
      • 1970-01-01
      • 1970-01-01
      • 2021-04-12
      • 2021-12-13
      • 2019-06-04
      • 2016-08-24
      • 1970-01-01
      • 2023-04-03
      相关资源
      最近更新 更多