我在网上看到过一段代码,它使用Swift Coble Do将JSON解码为 struct .
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let stringValue = try? container.decode(String.self, forKey: .someId), let value = Int64(stringValue) {
someId = value
} else {
someId = try container.decode(Int64.self, forKey: .someId)
}
}
此代码:
- 对字符串进行解码
- try 将其解析为
Int64
- 如果失败-它会直接try 对
Int64
进行解码
我的问题是--这个代码是多余的吗?
有没有可能String
中的Int64.init(_:)
能够破译出JSONDecoder.decode
不能破译的东西?
实际上,这不就是JSONDecoder
在幕后所做的事情吗?