我得到了这个 JSON:
{
"test":{
"0":{
"test":"test"
}
}
}
JSON 中的键只能是字符串,所以当我检索这个 json 时,我得到以下声明:
let myJson = [String: [String: Any]]()
现在我想过滤掉所有不能转换为整数的键,所以我想使用的字典是:
let myJson2 = [Int: [String: Any]]()
我如何compactMap
/filter
myJson
到myJson2
来过滤掉所有的Int
键并复制值?我明白了:
var myJson2 = [Int: [String: Any]]()
for (key, value) in myJson {
guard let keyInt = Int(key) else { return }
myJson2[keyInt] = value
}
但我正在寻找一个可以在 1 行内完成的 compactMap 解决方案
最佳答案
您可以在原始的键/值对序列上使用 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 }
最后一个
“赢”。
关于swift - 更改字典中键的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52678418/