在过去的 3-4 个小时里,我一直在尝试让这个愚蠢的东西正确解码这个枚举,现在对此感到非常沮丧!我有一个json
从 API 返回的字符串,如下所示:
[
{
"contractType": 0
}
]
我正在尝试将其映射到一个名为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)
}
}
}
我到底做错了什么!?任何帮助将不胜感激!