I'm decoding an API JSON response into a class called Company.
class Company: Codable {
let id: Int
let name: String?
...
}
One of the elements in the JSON response is called "enabledchat". enabledchat can either carry an INT (i.e. 1) to indicate the company has the chat feature enabled or it can carry a STRING (e.g. "Premium") to indicate that the company would need a "Premium" subscription to use the chat feature.
So Option 1 and 2 below both are legit API responses.
Option 1:
enabledchat: 1
Option 2:
enabledchat: "Premium"
QUESTION:
I would like to achieve 2 things:
- Setup Company: Codable in a way that
enabledchatcan hold both responses of type Int and String (i.e. both Option 1 and 2 above) - Then inject a separate, additional element
requiredsubscriptionintoCompanyduring Decode - i.e. ending up withenabledchat: Intandrequiredsubscription: Stringas 2 separate elements / properties in the Company class.
At the end of the decoding process, and instance of Company should look like this in case of Option 1 above:
{
id: 123
name: "mycompany"
enabledchat: 1
requiredsubscription: "-"
...
}
... and should look like this in case of Option 2 above:
{
id: 123
name: "mycompany"
enabledchat: 0
requiredsubscription: "Premium"
...
}
I believe the first part can be solved with the answers posted here: How to decode JSON value that can be either string or int
But I'm struggling with the second part - i.e. how to compute the value of element and inject that element into "Company" during the decoding process?