I am writing a program using Swift 4 and Xcode 9.2. I have faced difficulties with writing encodable class (exactly class, not struct). When I am trying to inherit one class from another, JSONEncoder does not take all properties from sub class (child). Please look at this:
class BasicData: Encodable {
let a: String
let b: String
init() {
a = "a"
b = "b"
}
}
class AdditionalData: BasicData {
let c: String
init(c: String) {
self.c = c
}
}
let encode = AdditionalData(c: "c")
do {
let data = try JSONEncoder().encode(encode)
let string = String(data: data, encoding: .utf8)
if let string = string {
print(string)
}
} catch {
}
It will print this: {"a":"a","b":"b"}
But I need this: {"a":"a","b":"b","c":"c"}
It look like c
property of class AdditionalData
just lost somewhere and somehow.
So question is: if I have class signed with protocol Encodable how to make sub class (child of this class, inherit) class properly?
I will be thankful for any help or advice.
Encodable
andDecodable
involve some code synthesis where the compiler essentially writes the code for you. When you conformBasicData
toEncodable
, these methods are written to theBasicData
class and hence they are not aware of any additional properties defined by subclasses. You have to override theencode(to:)
method in your subclass:See this question for a similar problem with
Decodable
.in my case, the base class did not need to be Codable really. Only the subclasses needed to be Codable. In that case, don't declare the base class as Codable, but only the subclasses. By doing so, you don't need to do any of this encode/codingKeys/init(from: Decoder) boilerplate stuff. Hope this helps for some people.