key的数据类型有时是Int/string时如何解析。下面是我到目前为止尝试过但不起作用的代码:
do {
// let value = try String(container.decode(Int.self, forKey: .Quantity))
let value = try container.decode(Int.self, forKey: .Quantity)
Quantity = value == 0 ? nil : String(value)
} catch DecodingError.typeMismatch {
Quantity = try container.decode(String.self, forKey: .Quantity)
}
谢谢
如果数据类型可能发生变化,您可以简单地尝试用不同的类型解析数据,如下所示:
if let intValue = try? container.decode(Int.self, forKey: .Quantity) {
// The integer value here
} else if stringValue = try? container.decode(String.self, forKey: .Quantity) {
// The string value here
}