Reputation: 37
I get the error:
Cannot initialize Role from invalid String value Mage
when I tried to interpret an array of string as enum type from a JSON file.
struct ChampionsData : Decodable{
let id : String
let key : String
let info : Info
let tags : [Role]
}
enum Role : String, CaseIterable, Decodable{
case Tank = "you believe that last person standing wins"
case Mage = "you like fantacies and tricking people"
case Assasin = "you enjoy living with danger"
case Fighter = "you are the warrior that built this town"
case Support = "you are a reliable teammate that always appears where you are needed "
case Marksman = "you tend to be the focus of the game, or the reason of victory or loss"
enum CodingKeys: String, CodingKey {
case mage = "Mage"
case assassin = "Assassin"
case tank = "Tank"
case fighter = "Fighter"
case support = "Support"
case marksman = "Marksman"
}
}
How can I parse it to a JSON object if I want to interpret tags as an array of Role enum type instead of an array of strings(or get rid of the error)?
Upvotes: 1
Views: 6641
Reputation: 1435
Your JSON
must be something like this
let jsonString = """
{
"id" :"asda",
"key" : "key asd",
"tags" : [
"Mage",
"Marksman"
]
}
"""
NOTE: I'm ignoring let info : Info
here.
And from this string enum should be Mage
, Marksman
.. so on
But you have added them to be
case Mage = "you like fantacies and tricking people"*
In Enum raw values are implicitly assigned as
CodingKeys
Update your code to this
enum Role : String, Decodable {
case tank = "Tank"
case mage = "Mage"
case assasin = "Assassin"
case fighter = "Fighter"
case support = "Support"
case marksman = "Marksman"
var value: String {
switch self {
case .tank:
return "you believe that last person standing wins"
case .mage:
return "you like fantacies and tricking people"
case .assasin:
return "you enjoy living with danger"
case .fighter:
return "you are the warrior that built this town"
case .support:
return "you are a reliable teammate that always appears where you are needed"
case .marksman:
return "you tend to be the focus of the game, or the reason of victory or loss"
}
}
}
Then you can just use the value after decoding like this
let data = jsonString.data(using: .utf8)!
// Initializes a Response object from the JSON data at the top.
let myResponse = try! JSONDecoder().decode(ChampionsData.self, from: data)
print(myResponse.tags.first?.value as Any)
If we used the json mentioned in the start we will get
"you like fantacies and tricking people"
Upvotes: 1