Actually I'm trying to Populate API JSON data to tableView but I cannot use enum as a string.
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)
}
}
}
You can define a computed property, e.g.
extension BillOfLading {
var stringValue: String {
switch self {
case .integer(let value): return String(value)
case .string(let value): return value
}
}
}
Then you can do
cell.bolLabel.text = data.bill_of_lading.stringValue