I have the following response from JSON service:
[
{
"id": 1,
"name": "Student"
},
{
"id": 2,
"name": "Faculty"
}
]
And I want to map it to an enum:
enum Role: Int, Codable, Identifiable {
case student
case faculty
var id: Int {
rawValue
}
}
But I am having trouble mapping since the array in JSON contains dictionaries.
2
Answers
Your objects have 2 member : id which is an Int and name which is a string that you want to use an enum for it :
example for decoding :
Edit: corrected type of name + coding key for enum
What you need is a custom encoder and decoder. Another issue in your code is that you are not specifying the integer value of your enumeration cases which should start with 1 (if you don’t specify it will start with zero). So your enumeration should look like this:
Then you can create a custom decoder:
And if you need to encode it as well a custom encoder:
Playground testing: