swift - 访问 Swift 嵌套字典中的行

标签 swift dictionary data-structures nested

我使用嵌套字典数据结构来跟踪一堆 NSLayoutConstraint,具体来说,[String: [String: NSLayoutConstraint]]。但对于我的情况,让我们考虑以下更简单的示例:

var myNestedDictionary = [String: [Int: Double]]()
myNestedDictionary["squares"] = [1: 1.0, 2: 4.0, 3: 9.0, 4: 16.0]
myNestedDictionary["cubes"] = [1: 1.0, 2: 8.0, 3: 27.0, 4: 64.0]
myNestedDictionary["factorials"] = [1: 1.0, 2: 2.0, 3: 6.0, 4: 24.0]

如何将所有提取到[Double]中,而不是键值对一个字典条目,例如如何从 myNestedDictionary["cubes"] 获取 [1.0, 8.0, 27.0, 64.0]

最佳答案

最简单的方法是将字典映射到数组:

let values = myNestedDictionary["cubes"]?.map({$0.1})

这不一定遵循键所暗示的顺序,因为字典是无序的。如果你想保持升序,你可以先对键进行排序,然后在映射中使用排序后的键:

let values = myNestedDictionary["cubes"]?.keys.sort().flatMap {myNestedDictionary["cubes"]![$0]!}

关于swift - 访问 Swift 嵌套字典中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36172154/

相关文章:

swift - 尝试将食物对象添加到数组导致崩溃在展开可选值时意外发现 nil

ios - Swift,按钮部分在 View 之外,我不会处理事件

c++ - C++ 中用于插入和删除的最佳数据结构/容器

data-structures - 数据结构 : insert, 删除、包含、获取随机元素,全部时间为 O(1)

swift - 如何检查开关中 UIButton 的 currentTitle?

python - 在保存中间值的同时多重映射一个值

python - 在列表/字典错误中搜索

python - 根据键的组合比较字典

javascript - 我应该在前端还是后端处理 JSON,哪个更快?

swift - 函数作为返回类型 Swift 4