【问题标题】:Using swift 4 Decodable protocol with RxSwift将 swift 4 可解码协议与 RxSwift 一起使用
【发布时间】:2017-12-27 14:24:26
【问题描述】:

我最近尝试使用 Decodable 协议将 JSON 解析为模型,并且我已经成功地做到了。但现在我想使用 RxSwift 实现双向绑定。为此,我需要声明“变量”类型的变量。这是我模型中的一个 sn-p:

struct Person : Decodable
{
    var batchcomplete = String()
    var `continue` = Continue()
    var query = Query()
    var limits = Limit()

    enum CodingKeys: String,CodingKey
    {
        case batchcomplete
        case `continue`
        case limits
        case query
    }

    init(from decoder: Decoder) throws
    {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        batchcomplete = try container.decode(String.self, forKey: .batchcomplete)
        `continue` = try container.decode(Continue.self, forKey: .`continue`)
        limits = try container.decode(Limit.self, forKey: .limits)
        query = try container.decode(Query.self, forKey: .query)
    }
}

现在,如果我将“批处理完成”从 String() 更改为 Variable,init() 方法会引发错误:

No 'decode' candidates produce the expected contextual result type 'Variable<String>'.

进行这些更改,您将收到错误消息。

var batchcomplete = Variable<String>("")
batchcomplete = try container.decode(Variable<String>.self, forKey: .batchcomplete)

【问题讨论】:

    标签: json protocols swift4 rx-swift decodable


    【解决方案1】:

    不要尝试解码为Variable ...只需设置它的值:

    batchcomplete.value = try container.decode(String.self, forKey: .batchcomplete)
    

    或者你也可以声明你的实例变量并在你的 init 中初始化一次:

    let batchcomplete: Variable<String>
    batchcomplete = Variable<String>(try container.decode(String.self, forKey: .batchcomplete))
    

    附带说明,您的 Variable 应声明为常量 (let),因为您更改了 Variable 中包含的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-30
      • 2017-11-07
      • 2018-04-01
      • 2018-10-30
      • 2011-12-11
      • 2020-01-13
      • 1970-01-01
      相关资源
      最近更新 更多