【问题标题】:Change the type of the key in a dictionary更改字典中键的类型
【发布时间】:2018-10-06 19:44:58
【问题描述】:

我得到了这个 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
}

但我正在寻找一种使用 compactMap 的解决方案,它可以在 1 行中完成

【问题讨论】:

    标签: swift dictionary


    【解决方案1】:

    您可以在原始的键/值对序列上使用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 })
    

    相反。附加参数确定哪个值 用于重复key的情况,{ $1 }最后一个 “赢了”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-22
      • 1970-01-01
      • 2020-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      相关资源
      最近更新 更多