swift - 更改字典中键的类型

标签 swift dictionary

我得到了这个 JSON:

{
  "test":{
    "0":{
      "test":"test"
    }
  }
}

JSON 中的键只能是字符串,所以当我检索这个 json 时,我得到以下声明:

let myJson = [String: [String: Any]]()

现在我想过滤掉所有不能转换为整数的键,所以我想使用的字典是:

let myJson2 = [Int: [String: Any]]()

我如何compactMap/filter myJsonmyJson2 来过滤掉所有的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/

相关文章:

ios - 如何在 UI TextView 中显示 YouTube 搜索 API 响应?

swift - 无法单击对象并将其拖动到 ViewController

c# 检查键是否存在于字典中然后传递它的值

python - 在 Python 中将字符串列表转换为字典

swift - 无法构建或存档运行良好的 Xcode 项目

ios - 在 tableView 中显示自定义表格分隔符 UIView

arrays - 如何使用 SwiftyJSON 将 JSON 数组转换为数组

ios - iPhone Xcode PDF map 位置 GPS

python - 来自 python 字典的图形 networkx

c# - 预声明变量总是必要的吗?