实际上,我正在尝试将API JSON数据填充到tableView中,但是不能将enum用作字符串。
struct Results: Codable {
let container_id : Int?
let container_number : String?
let shipment_id : Int?
let bill_of_lading : BillOfLading
let eta : String?
let discharge_port_id : Int?
let discharge_port_name : String?
let consignee_id : Int?
let consignee_name : String?
let customer_id : Int?
let customer_name : String?
let shipment_status : String?
let container_status : String?
let user_id : Int?
let user_display_name : String?
let commodities : [Commodities]
let all_sold : Bool?
let quantities : Quantities
let sales : [String]?
let sales_report : Sales_report
let commodities_summary : String?
let commodity_quantity_summary : String?
let commodities_summary_en : String?
let commodity_quantity_summary_en : String?
}
enum BillOfLading: Codable {
case integer(Int)
case string(String)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let x = try? container.decode(Int.self) {
self = .integer(x)
return
}
if let x = try? container.decode(String.self) {
self = .string(x)
return
}
throw DecodingError.typeMismatch(BillOfLading.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for BillOfLading"))
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .integer(let x):
try container.encode(x)
case .string(let x):
try container.encode(x)
}
}
}
答案 0 :(得分:1)
您可以定义一个计算属性,例如
extension BillOfLading {
var stringValue: String {
switch self {
case .integer(let value): return String(value)
case .string(let value): return value
}
}
}
那你就可以做
cell.bolLabel.text = data.bill_of_lading.stringValue
答案 1 :(得分:0)
您正在使用cell.bolLable.text = dataa.bill_of_lading
其中bill_of_lading
是BillOfLading
类型,
和bolLable.text
仅接受字符串类型。
尝试cell.bolLable.text = dataa.bill_of_lading.string
答案 2 :(得分:-1)
这是一种对我来说很好的解决方法
// MARK: - Imagefile
struct Imagefile : Codable
{
let large, thumb: String?
let pageName: String?
let pageKey: BookType?
enum CodingKeys: String, CodingKey {
case large, thumb
case pageName = "page_name"
case pageKey = "page_key"
}
}
enum BookType: Codable {
case int(Int)
case string(String)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let x = try? container.decode(Int.self) {
self = .int(x)
return
}
if let x = try? container.decode(String.self) {
self = .string(x)
return
}
throw DecodingError.typeMismatch(BookType.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for BookType"))
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .int(let x):
try container.encode(x)
case .string(let x):
try container.encode(x)
}
}
}
我在这里使用BookType。