我有一个符合Decodable协议的类(从API获取数据),我想将它保存在Realm数据库中。当我的一个属性是数组(List)时出现问题。它说Cannot automatically synthesize Decodable because List<Item> does not conform to Decodable
绕过这个问题的最佳方法是什么? Realm只支持基本类型的数组。
这是我的班级:
class PartValue: Object, Decodable {
@objc dynamic var idetifier: Int = 0
let items = List<Item>()
}
答案 0 :(得分:2)
使用在Swift 4.1中实现的期待已久的条件一致性,如果List
符合Decodable
,您可以简单地声明Element
符合Decodable
。
extension List: Decodable where List.Element: Decodable {
public convenience init(from decoder: Decoder) throws {
self.init()
var container = try decoder.unkeyedContainer()
let array = try container.decode(Array<Element>.self)
self.append(objectsIn: array)
}
}
要使这项功能符合您的具体情况,您需要确保Item
也符合Decodable
。
如果您还需要Encodable
一致性,只需将List
扩展为支持该版本。
extension List: Encodable where List.Element: Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(contentsOf: Array(self))
}
}
答案 1 :(得分:0)
Dávid的解决方案并不完全适合我。我不得不调整解决方案,而不是将decoder.unkeyedContainer()
替换为decoder.singleValueContainer()
,下面是解决方案。
extension List: Decodable where List.Element: Decodable {
public convenience init(from decoder: Decoder) throws {
self.init()
let container = try decoder.singleValueContainer()
let array = try container.decode([Element].self)
self.append(objectsIn: array)
}
}