首页 > 解决方案 > 快速词典:地图中的地图

问题描述

我想将从 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]
        )
    })

有什么想法吗?

标签: swiftdictionaryenums

解决方案


我想将从 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)
}

推荐阅读