无法在swift中将枚举从Json转换为字符串
我得到一个错误: 无法从无效的字符串值Mage初始化角色 当我试图从JSON文件中将字符串数组解释为枚举类型时无法在swift中将枚举从Json转换为字符串,swift,enums,decode,Swift,Enums,Decode,我得到一个错误: 无法从无效的字符串值Mage初始化角色 当我试图从JSON文件中将字符串数组解释为枚举类型时 struct ChampionsData : Decodable{ let id : String let key : String let info : Info let tags : [Role] } enum Role : String, CaseIterable, Decodable{ case Tank = "you believe
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"
}
}
如果我想将标记解释为角色枚举类型的数组而不是字符串数组(或消除错误),如何将其解析为JSON对象?您的
JSON
必须是这样的
let jsonString = """
{
"id" :"asda",
"key" : "key asd",
"tags" : [
"Mage",
"Marksman"
]
}
"""
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)
注意:我忽略了这里的let info:info
并且从这个字符串枚举应该是Mage
,Marksman
。。依此类推
但是你已经把它们加在一起了
case Mage = "you like fantacies and tricking people"*
在枚举中,原始值隐式指定为CodingKeys
将您的代码更新到此
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"
}
}
}
然后你可以像这样解码后使用这个值
let jsonString = """
{
"id" :"asda",
"key" : "key asd",
"tags" : [
"Mage",
"Marksman"
]
}
"""
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)
如果我们使用开头提到的json,我们将得到
"you like fantacies and tricking people"
Swift 3.0后的枚举应该是用
小写
而不是大写
编写的,非常感谢Razi,我花了这么多时间来编写它,您的解决方案解决了我的错误!