Problem is List type does not conform to Codable, the below class cannot be insert to Realm.
for example,
class Book: Codable {
var name: String = ""
var author: String = ""
var tags = [String]()
}
Consider the above class conforms to Codable, if store this class to Realm, it needs to use List<Object> type instead of [String]
class Book: Object, Codable {
@objc dynamic var name: String = ""
@objc dynamic var author: String = ""
var tags = List<Tag>()
required convenience init(from decoder: Decoder) throws {
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
author = try container.decode(String.self, forKey: .author)
tags = try container.decode(List<Tag>.self, forKey: .tags) // this is problem.
}
}
class Tag: Object, Codable {
@objc dynamic var string: String = ""
required convenience init(from decoder: Decoder) throws {
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
string = try container.decode(String.self, forKey: .string)
}
}
To conform to Codable, it should be implement Decodable protocol. (required convenience init(from decoder: Decoder) throws)
But, List type does not conform to Codable(Decodable), it is impossible to use Codable if the class has List type.
How to resolve this issue?
Thanks,
Codable. - Dávid Pásztor