swift - 快速词典:地图中的地图
问题描述
我想将从 API 获得的值转换为特定格式。
[String:Any] // format received
[Int:[ContentType:Int]] // required format
ContentType 是一个枚举
数据示例可能如下所示:
["123":["Tables":"25","Chairs":"14"]] // input
[123:[.Tables:25,.Chairs:14]] // output
我想我需要在地图中有一张地图才能工作,但我正在努力寻找前进的方向。不过,我很可能完全是在叫错树。我真的不想手动循环并一次添加每个项目;如果可能的话,我正在寻找比这更智能的东西。
enum ContentType: String {
case Tables,Chairs
}
let original_values: [String:Any]
= ["1234":["Tables":"5","Chairs":"2"]]
let values: [Int:[ContentType:Int]]
= Dictionary(uniqueKeysWithValues: original_values.map {
(
Int($0.key)!,
(($0.value as? [String:String]).map { // Error on this line - expects 1 argument but two were used
(
ContentType(rawValue: $1.key)!, // $1 is presumably wrong here?
Int($1.value)
)
}) as? [ContentType:Int]
)
})
有什么想法吗?
解决方案
我想将从 API 获得的值转换为特定格式。
你可以让你的枚举Decodable
enum ContentType: String, Decodable {
case tables, chairs
enum CodingKeys: String, CodingKey {
case Tables = "Tables"
case Chairs = "Chairs"
}
}
然后你可以解码收到Data
,然后compactMap
将其格式化(Int, [ContentType: Int])
。您可以Dictionary
使用设计的初始化程序将这些元组转换为
do {
let decoded = try JSONDecoder().decode([String: [ContentType: Int]].self, from: data)
let mapped = Dictionary(uniqueKeysWithValues: decoded.compactMap { (key,value) -> (Int, [ContentType: Int])? in
if let int = Int(key) {
return (int, value)
} else {
return nil
}
})
} catch {
print(error)
}
推荐阅读
- angular - 如何访问离子中的联系人列表
- html - 多行
和
- python - 在 PySpark UDF 中使用广播值抛出“java.io.IOException:无法删除原始文件”
- php - Reactjs - axios 发布请求不起作用 - 找不到 404
- flutter - 限制 TextField 中允许的字符数
- javafx - JavaFx:在表格单元格内显示一个图标
- python - 给定一个字符串输入,如何检查是否存在同名变量
- php - Docker-compose up:获取服务器 API 版本时出错:('连接中止。',ConnectionRefusedError(61,'连接被拒绝'))
- javascript - 这个视图类方法 display() 不起作用?
- flutter - 使用 firebase_ml_vision 时出现颤振错误