Convert this
[
"Cat" : ["A" : 1, "B": 2],
"Mat" : ["C" : 3, "D": 4]
]
Into
[
"A" : 1,
"B" : 2,
"C" : 3,
"D" : 4
]
不使用循环。换句话说,使用像reduce、flatmap这样的函数。
source
可以是类型 Dictionary<String,Dictionary<String,String>>
到目前为止,我已经成功地将字典简化为字典数组
let flatten = source.flatMap({ (k,v) -> [String: String]? in
return v
})
// flatten = [["A" : 1, "B": 2], ["C" : 3, "D": 4]]]
最佳答案
一个选项:
let dictionary = [
"Cat" : ["A" : 1, "B": 2],
"Mat" : ["C" : 3, "D": 4]
]
let merged = dictionary
// take values, we don't care about keys
.values
// merge all dictionaries
.reduce(into: [:]) { (result, next) in
result.merge(next) { (_, rhs) in rhs }
}
print(merged) // ["B": 2, "A": 1, "C": 3, "D": 4]
关于ios - Swift 减少/展平字典<String,Dictionary> 到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49704613/