此问题在此处已有答案:
Using codable with value that is sometimes an Int and other times a String(6个答案)
19天前关闭
当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)
}
字符串
谢谢
1条答案
按热度按时间atmip9wb1#
如果数据的类型可能会更改,您可以简单地尝试使用不同的类型解析数据,如下所示:
字符串
您也可以使用
do-catch
来处理解析错误,如下所示:型