我最近尝试使用Decodable协议将JSON解析为模型,并且我已经成功完成了。但现在我想使用RxSwift实现双向绑定。为此,我需要声明类型为'变量<>' .Here的变量是我的模型的片段:
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)
答案 0 :(得分:4)
请勿尝试解码为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
中包含的值。