转换这个

[
   "Cat" : ["A" : 1, "B": 2],
   "Mat" : ["C" : 3, "D": 4]
]

进入
[
    "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 - 将Dictionary <String,Dictionary>转换为字典,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49704613/

10-14 20:05