【发布时间】: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