gpt4 book ai didi

ios - Swift 减少/展平 Dictionary 到 Dictionary

转载 作者:可可西里 更新时间:2023-11-01 01:09:03 25 4
gpt4 key购买 nike

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>>


到目前为止,我已经设法将 Dictionary 缩减为一个 Dictionary 数组

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 减少/展平 Dictionary<String,Dictionary> 到 Dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49704613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com