【发布时间】:2019-03-14 14:26:38
【问题描述】:
我正在尝试将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)
【问题讨论】:
-
case pizza = String这没有意义。只需写case pizza(为所有人)。 -
我认为应该是
String,因为它在Structs中的外观。当时对我来说很有意义。为什么我要为所有不同的食物添加case pizza?您必须指的是case,然后是相应的食物。
标签: json swift string enums decodable