【发布时间】:2018-02-05 09:12:13
【问题描述】:
所以,我正在使用领域,并且两个模型之间存在以下关系:A unit has many tests:
// Unit model
class Unit: Object, Decodable {
@objc dynamic var id: String = ""
...
let tests = List<Test>()
enum CodingKeys: String, CodingKey {
case id
...
//case tests = "complete_control_tests"
}
convenience required init(from decoder: Decoder) throws {
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(String.self, forKey: .id)
...
if let arr = try container.decodeIfPresent(Array<Test>.self, forKey: .tests) {
tests.append(objectsIn: arr)
} else {
self.tests.append(objectsIn: [])
}
}
}
// Test model
class Test: Object, Decodable {
@objc dynamic var id: String = ""
@objc dynamic var room_control_id: String = ""
enum CodingKeys: String, CodingKey {
case id
case room_control_id = "room_control_id"
}
}
当 tests 属性被注释时,我可以正确解析该模型的 json 输出。但是当我取消注释时,我有以下错误:
Swift.Encodable:12:17: Protocol requires function 'encode(to:)' with type 'Encodable'
Models/Unit.swift:27:6: Cannot automatically synthesize 'Encodable' because 'List<Test>' does not conform to 'Encodable'
有没有办法让 Codable 和 Realm 玩得更好?
【问题讨论】:
标签: swift realm swift4 codable