将 Enum 与 JSON (Swift) 一起使用时出现错误

Getting Errors when using Enum with JSON (Swift)

我正在尝试将 DecodableEnum 一起使用,但我的 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)

在这种情况下,literal 是实际的 String 而不是 type。试试这个...

enum BusinessType : String, Decodable {
    case pizza = "pizza"
    case seafood = "seafood"
    case greek = "greek"
    case vegan = "vegan"
}

如果您将原始值的类型指定为 String,则不必写入其原始值,因为默认值是案例名称

enum BusinessType : String, Decodable {
    case pizza, seafood, greek, vegan
}