Is there a way to decode a JSON that is a list of objects when some of these objects can't be decoded properly? Let's say I have a enum
with 2 possible values foo
and bar
but all of sudden backend starts to return another possible option for that field (let's say other
).
Looking to the example below, first part is fine. What I wanted is to have in the second part, a list containing 1 element (foo
), instead of nil
.
import Foundation
enum Value: String, Codable {
case foo
case bar
}
struct Object: Codable {
let value: Value
}
let dataList = "[{\"value\":\"foo\"}, {\"value\":\"bar\"}]".data(using: .utf8)!
let objectList = try? JSONDecoder().decode([Object].self, from: dataList) // [{foo}, {bar}]
let anotherDataList = "[{\"value\":\"foo\"}, {\"value\":\"other\"}]".data(using: .utf8)!
let anotherObjectList = try? JSONDecoder().decode([Object].self, from: anotherDataList) // nil
// is there a way to have this ^ as [{foo}] instead of nil?