Hi.
I've moving over a small project to use Codable. But unfortunatley I'm running into an issue with saving keys in the base class?
Any clues to what I'm doing wrong. It's hopefully something obvious as I've only just started using it.
Heres the error..
keyNotFound(__lldb_expr_77.base.(CodingKeys in _DFBA3185686E54C6A13CADA5FE9CB15B).uuid, Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key uuid (\"uuid\").", underlyingError: nil))
Heres a simple playground example to demonstrate the issue and which throws the previous error..
class base:Codable{
var uuid = "NONE"
init(){
uuid = UUID().uuidString
}
private enum CodingKeys: String, CodingKey {
case uuid
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.uuid = try container.decode(String.self, forKey: .uuid)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.uuid, forKey: .uuid)
}
}
class middle:base{
var number:Int
override init(){
self.number = 2
super.init()
}
private enum CodingKeys: String, CodingKey {
case number
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.number = try container.decode(Int.self, forKey: .number)
let superdecoder = try container.superDecoder()
try super.init(from: superdecoder)
}
override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.number, forKey: .number)
let superdecoder = container.superEncoder()
try super.encode(to: superdecoder)
}
}
let test = middle()
if let jsonData = try? JSONEncoder().encode(test) {
if let jsonString = String(data: jsonData, encoding: .utf8){
let data = jsonString.data(using: .utf8)
do {
let obj = try JSONDecoder().decode(base.self, from: data!)
print (obj)
} catch {
print("\(error)")
}
}
}
Thanks