你可以用
compactMap
关于原语的键/值对序列
字典来提取那些带有整数键的,以及
Dictionary(uniqueKeysWithValues:)
创建新词典:
let myDict: [String: [String: Any]] = [
"test": [ "0": [ "test" : "test" ]],
"123": [ "1" :[ "foo": "bar" ] ]
]
let myDict2 = Dictionary(uniqueKeysWithValues: myDict.compactMap { (key, value) in
Int(key).map { ($0, value) }
})
print(myDict2) // [123: ["1": ["foo": "bar"]]]
print(type(of: myDict2)) // Dictionary<Int, Dictionary<String, Any>>
不同的
整数。如果那样的话
不保证那么用
let myDict2 = Dictionary(myDict.compactMap { (key, value) in
Int(key).map { ($0, value) }
}, uniquingKeysWith: { $1 })
在重复键的情况下使用
{ $1 }
最后一个
胜利。