Looking for some input as to how you would handle the scenario I recently ran into.
I have been using Swift 4s Codable with success but today noticed a crash that I didn't expect. The API that I am working with, says it returns a boolean
for the key manage_stock
.
My stubbed struct looks like:
struct Product: Codable {
var manage_stock: Bool?
}
That works fine, the problem is that the API sometimes returns a string
instead of a boolean
.
Because of this, my decode fails with:
Expected to decode Bool but found a string/data instead.
The string only ever equals "parent"
and I want it to equate to false
.
I am also fine with changing my struct to var manage_stock: String?
if that makes things easier to bring the JSON data in from the API. But of course, if I change that, my error just changes to:
Expected to decode String but found a number instead.
Is there a simple way to handle this mutation or will I need to lose all the automation that Codable
brings to the table and implement my own init(decoder: Decoder)
.
Cheers