If we encoded objects of a Class that conforms to Codable
and would like to decode these objects using a new class code that has a new property, what code would be required to make that new property non-optional, and give it property a default value?
Old class:
class Item: Codable {
let id: String
}
New class:
class Item: Codable {
let id: String
let title: String
}
When decoding objects saved in the old format using the new format's code, no title
property will be found, and decoding will not work.
We could fix that by making title
an optional String?
.
But how would we achieve keeping title
as a non-optional String
, and giving it a default value when decoding each object?
PS: This is the full code. No Coding Keys were specified, and no custom init from decoder written.