【问题标题】:Swift: convert [Dictionary<String, [String : Double]>.Element] to [String : [String : Double]]Swift:将 [Dictionary<String, [String : Double]>.Element] 转换为 [String : [String : Double]]
【发布时间】:2021-09-10 11:02:17
【问题描述】:

我有这个 JSON 字符串:

[
    {
        "name": "first_category",
        "model": {
            "OK": 0.49404761904761907,
            "NOPE": 0.48214285714285715
        }
    },
    {
        "name": "second_category",
        "model": {
            "YOP": 0.389338593,
            "GO": 0.20420894
        }
    }
]

我创建了这个结构来解码它:

struct JSONModel: Codable {
    let name: String
    let model: [String: Double]
}

解码:

let decodedModel = try? decoder.decode([JSONModel].self, from: Data(jsonString.utf8))

它按预期正确填充了数组,但现在我想使用这个数组创建一个字典,其键是JSONModel 名称,并为模型赋值。这是我期望得到的:

[
    "first_category": [
        "OK": 0.49404761904761907, 
        "NOPE": 0.4821428571428571
    ],
    "second_category": [
        "YOP": 0.389338593, 
        "GO": 0.20420894
    ]
]

所以我尝试了这个:

let simplifiedModel: [String: [String: Double]] = decodedModel.flatMap { [$0.name: $0.model] }

但是我收到了这个错误:

无法将 '[Dictionary.Element]' 类型的值转换为闭包结果类型 '[String : [String : Double]]'

我应该怎么做?

感谢您的帮助

【问题讨论】:

  • 如果你删除了类型 ``` [String: [String: Double]]``` 的简化模型会发生什么。
  • @RajaKishan 是的,这行得通,但我想把它作为[String: [String: Double]]
  • 你不能 (flat)Map 一个数组到字典。 flatMap 的结果是一个 array 元组。

标签: swift dictionary


【解决方案1】:

我会为此使用reduce(into:)

let dictionary = decodedModel.reduce(into: [:]) { 
    $0[$1.name] = $1.model
}

【讨论】:

  • default: [String: Double]() 不需要,因为model 不是可选的,不是吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-10
  • 1970-01-01
  • 1970-01-01
  • 2014-10-22
  • 2012-07-19
相关资源
最近更新 更多