【问题标题】:How to write a transformer in codable?如何用可编码的方式编写变压器?
【发布时间】:2018-12-14 12:49:33
【问题描述】:

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

struct SampleModel: Codable {
    let showId: String
}

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

Codable有什么办法吗?

【问题讨论】:

  • 创建查找并进行手动解码
  • 只使用 Codable,不。事实上,你想做的大部分事情都不会涉及 Codable,而是字符串操作。现在,我将忽略 Codable 部分并弄清楚如何将 one 映射到 firsttwosecond 等等。
  • 我使用了 mantle 框架,我们可以在其中编写转换器来更改值,如果它是一个类,那么覆盖 setter 方法可能会起作用。 .@CalebKleveter,我的输入集非常少,只有 10 个,我可以通过创建字典(其他语言的哈希图)来做到这一点。

标签: ios swift codable


【解决方案1】:

如果我理解正确

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
        }
     }
}

【讨论】:

  • 这正是我想要的。
猜你喜欢
  • 1970-01-01
  • 2019-09-04
  • 1970-01-01
  • 1970-01-01
  • 2020-01-31
  • 2017-08-11
  • 1970-01-01
  • 2011-02-19
  • 1970-01-01
相关资源
最近更新 更多