簡體   English   中英

在 Swift 5 中解碼枚舉 - 這不可能這么難

[英]Decoding enum in Swift 5 - This CANNOT be this hard

在過去的 3-4 個小時里,我一直在嘗試讓這個愚蠢的東西正確解碼這個枚舉,現在對此感到非常沮喪! 我有一個從 API 返回的json字符串,如下所示:

[
  {
    "contractType": 0
  }
]

我正在嘗試將 map 指向一個名為ContractType的枚舉。 這是我的整個ContractType枚舉

enum ContractType: Int {
    case scavenger = 0
}

這是我的擴展,我試圖使其符合Codable協議。

extension ContractType: Codable {
    enum Key: Int, CodingKey {
        case rawValue
    }

    enum CodingError: Error {
        case unknownValue
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: Key.self)
        let rawValue = try? container.decode(Int.self, forKey: .rawValue)

        switch rawValue {
        case 0:
            self = .scavenger
        default:
            throw CodingError.unknownValue
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: Key.self)
        switch self {
        case .scavenger:
            try container.encode(0, forKey: .rawValue)
        }
    }
}

我到底做錯了什么?? 任何幫助將不勝感激!

要解析上述Codable響應,可編碼模型應該是,

struct Response: Codable {
    let contractType: ContractType
}

enum ContractType: Int, Codable {
    case scavenger = 0
}

現在,像這樣解析JSON data

do {
    let response = try JSONDecoder().decode([Response].self, from: data)
    print(response)
} catch {
    print(error)
}

無需顯式實現init(from:)encode(to:) 它將由編譯器自動處理。

這就是你所需要的。

struct Contract: Codable {
    var contractType: ContractType

    enum ContractType: Int, Codable {
        case scavenger
    }
}

do {
    let contract = try JSONDecoder().decode([Contract].self, from: json)
    print(contract.contractType)
} catch {
    print(error)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM