Such feature of Swift as Codable
(Decodable
&Encodable
) protocol is very useful.
But I found such issue:
Let we have class Parent conforming to Codable
:
class Parent: Codable {
var name: String
var email: String?
var password: String?
}
Ok, that class is conforming to Codable protocol "from the box", you don't need write any initializers, it's ready to be initialized from JSON like that:
{ "name": "John", "email": "johndoe@yahoo.com", "password": <null>}
But let's say we need other class, Child inherits from Parent and be conforming to Codable:
class Child: Parent {
var token: String
var date: Date?
}
so class Child must be conforming to Codable by conformance to Parent, BUT properties of class Child won't be initialized from JSON properly. Decision I found is write all Codable stuff for class Child by myself, like:
class Child: Parent {
var token: String
var date : Date?
enum ChildKeys: CodingKey {
case token, date
}
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let container = try decoder.container(keyedBy: ChildKeys.self)
self.token = try container.decode(String.self, forKey: .token)
self.date = try container.decodeIfPresent(Date.self, forKey: .date)
}
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: ChildKeys.self)
try container.encode(self.token, forKey: .token)
try container.encodeIfPresent(self.date, forKey: .date)
}
}
But I feel it can't be right, did I missed something? How to make class Child conforming to Codable properly without writing all that stuff?