Inheritance of Encodable Class
Encodable
and Decodable
involve some code synthesis where the compiler essentially writes the code for you. When you conform BasicData
to Encodable
, these methods are written to the BasicData
class and hence they are not aware of any additional properties defined by subclasses. You have to override the encode(to:)
method in your subclass:
class AdditionalData: BasicData {
let c: String
let d: Int
init(c: String, d: Int) {
self.c = c
self.d = d
}
private enum CodingKeys: String, CodingKey {
case c, d
}
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.c, forKey: .c)
try container.encode(self.d, forKey: .d)
}
}
See this question for a similar problem with Decodable
.