代码之家  ›  专栏  ›  技术社区  ›  Dipesh

如何用codable编写一个转换器?

  •  -3
  • Dipesh  · 技术社区  · 6 年前

    让我们考虑一个场景,我想在其中填充模型 Codable 如下所示。

    struct SampleModel: Codable {
        let showId: String
    }
    

    我们从服务器收到的响应是“showId:”one“。但是,我想将它保存为“First”而不是“one”。

    有什么办法 可编码的 ?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Shehata Gamal    6 年前

    如果我没弄错的话

    struct SampleModel: Codable {
        let showId: String
        enum CodingKeys: String, CodingKey {
            case showId
        }
    
        init(from decoder: Decoder) throws {
    
            let container = try decoder.container(keyedBy: CodingKeys.self)
    
            do {
    
                let id = try container.decode(String.self, forKey: .showId)
                let stored = id == "one" ? "First" : "default"
                self.init(showId:stored)
    
            } catch {
                print(error)
                throw error
            }
         }
    }