Note: saw this question but doesn't seem to resolve the issue: Swift Dynamically choose Codable struct for JSON field value based on response type
I don't know the runtime type before hand since decoding from a network call response. So currently I am attempting to decode in a try/catch one after another, but I am looking for a more concise way to do that based on a common property which could be used for a theoretical "switch" to define the runtime type.
I know that they always have a field with a key which can be mapped to the final type so is there a trick to use here? I am thinking something along the lines of a union type holding one of the possible results. Here is the example code I have:
struct Result1: Codable {
let resultType: String = "result1" // this is always the case in the JSON for this particular type of result
...
let other fields which are unique to this type of result
}
struct Result2: Codable {
let resultType: String = "result2" // always this field in the json for this result type
...
let other fields which are unique to this type of result ...
}
... Lot's of other types ...
struct ResultN: Codable {
let resultType: String = "resultN"
....
}
// Now how to decode the "either Result1 or Result2 or .... ResultN
let value = try JSONDecoder().decode(????.self, from: data) // don't know what type it will be yet
if value is Result1 { ... handle this case ... }
if value is Result2 { ... handle this case ... }
....
if value is ResultN { ..... }
Perhaps decode to a general Json dictionary and from there map to the correct type?
Note:
Considering this mechanism (but lots of boiler plate):
let dict = try JSONSerialization.jsonObject(with: data) as? [String: Any]
switch dict["resultType"] {
case "result1" : ... decode to res1
...
case "resultN" : .... decode to resN
Using Dictionary of resultType to Codable maybe enough (JSON Decoding runs twice to get
dictandvalue)