【问题标题】:Getting Errors when using Enum with JSON (Swift)将 Enum 与 JSON (Swift) 一起使用时出现错误
【发布时间】:2019-03-14 14:26:38
【问题描述】:

我正在尝试将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)

【问题讨论】:

  • case pizza = String 这没有意义。只需写case pizza(为所有人)。
  • 我认为应该是String,因为它在Structs 中的外观。当时对我来说很有意义。为什么我要为所有不同的食物添加case pizza?您必须指的是case,然后是相应的食物。

标签: json swift string enums decodable


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-27
      • 2021-06-25
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      相关资源
      最近更新 更多