我正在尝试将Decodable
与Enum
一起使用,但是在我的Enum
中出现四个错误,该错误指出: 枚举大小写的原始值必须为文字 。我是处理JSON数据的新手,我不确定如何使它工作。
import UIKit
enum BusinessType : String, Decodable {
case pizza = String
case seafood = String
case greek = String
case vegan = String
}
struct Address : Decodable {
var street : String
var city : String
var state : String
var businessType : BusinessType
}
struct Customer : Decodable {
var firstName : String
var lastName : String
var address : Address
}
struct CustomersResponse : Decodable {
var customers : [Customer]
}
let json = """
{
"customers":[
{
"firstName" : "My",
"lastName" : "Client",
"address" : {
"street" : "100 Business Address",
"city" : "New York",
"state" : "NY",
"businessType" : "pizza"
}
}
]
}
""".data(using: .utf8)!
let customersResponse = try!
JSONDecoder().decode(CustomersResponse.self, from: json)
print(customersResponse)
答案 0 :(得分:0)
在这种情况下,literal
是实际的String
,而不是type
。试试这个...
enum BusinessType : String, Decodable {
case pizza = "pizza"
case seafood = "seafood"
case greek = "greek"
case vegan = "vegan"
}
答案 1 :(得分:0)
如果您将原始值的类型指定为String
,则不必写入其原始值,因为默认值是案例名称
enum BusinessType : String, Decodable {
case pizza, seafood, greek, vegan
}