ios - 如何使用enum获取字符串值

标签 ios arrays swift uitableview cell

实际上,我正在尝试将 API JSON 数据填充到 tableView,但我无法将枚举用作字符串。

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)
        }
    }
}

This is the error picture

最佳答案

您可以定义计算属性,例如

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

关于ios - 如何使用enum获取字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59464651/

相关文章:

ios - 根据 Xcode UI 测试是否运行定义全局变量

IOS Enterprise Distribution 更新会保留用户数据吗?

ios - 选择一个按钮后,如何取消选择阵列中的所有其他按钮?

c++ - 将 operator new(sizeof(T) * N) 返回的内存视为数组

ios - 具有删除对象的值类型的 Realm

ios - 试图从 appdelegate 设置窗口

ios - 无法更改导航栏颜色

php - 尝试对单个 mysql 查询中的数据进行排序和显示

ios - 如何将数据从 ViewController 传递到 UITabBarController -> UINavigationController -> ViewController

swift - "let"和 "static let"有什么区别?