I'm decoding a simple structure and ran into unexpected behavior.
struct Contacts: Codable {
struct Recipient: Codable {
let name: String
}
let recipients: [Recipient]
}
do {
let jsonData = SOME STING WITH VALID JSON
let contacts = try JSONDecoder().decode(Contacts.self, from: jsonData)
}
catch {
}
This decodes just fine. If I do this simple change to the structure, it no longer decodes.
struct Contacts: Codable {
struct Recipient: Codable {
let name: String
}
let recipients: [Recipient] = []
}
Now JSONDecoder won't decode the exact same string. Why does the default initialization of the array cause the decoder to stop working?
letand can’t be changed once it is initialized?letproperty can only be set once so if you're giving it a default value then the initializer generated byCodablecan't set it again. If you change it tovarit will decode. It will still fail to decode if the recipients key isn't present in the json though which is what I'm assuming you were trying to preventdecodeIfPresent([Recipient].self forKey: .recipient) ?? []to default initialize it..init(from decoderwith custom behavior. If instances of the struct are created without the decoder add aninitmethod providing a default value.