For a given JSON like below:
{
"store": {
"animals": [
{
"type": "dog"
},
{
"type": "cat"
}
]
}
}
I can parse it with enum for type
like following:
final class AnimalStore: Decodable {
let store: Store
}
extension AnimalStore {
struct Store: Decodable {
let animals: [Animal]
}
}
extension AnimalStore.Store {
struct Animal: Decodable {
let type: AnimalType?
}
}
extension AnimalStore.Store.Animal {
enum AnimalType: String, Decodable {
case dog = "dog"
case cat = "cat"
//case unknown = how such a case could be implemented?
}
}
And also since it is optional; it would work fine if type
key value pair would be missing from json.
But I would like to have another case, lets call it unknown
so that if any given type is not dog or cat (string being something else),type would be initialised as unknown. Right now it crashes if a type, other than dog or cat is given.
How initialising with another type other than the ones given can be implemented with enum?
In other words, for a given type like: "type": "bird"
I would like type
to be initialised as unknown
.