这个Int64 Swift解码是多余的吗



我在网上看到一段代码,它使用Swift Codable将JSON解码为结构。

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)
}
}

此代码:

  • 解码字符串
  • 尝试将其解析为Int64
  • 如果失败,则直接尝试解码Int64

我的问题是-这个代码是多余的吗?

是否存在来自StringInt64.init(_:)能够解码JSONDecoder.decode不能解码的东西的情况?

事实上,这不是";解码字符串-初始化Int64";和JSONDecoder在引擎盖下做的完全一样?

这不是多余的。它可以用于处理JSON,该JSON有时将数字编码为字符串(在引号中(,有时仅将数字编码。

例如,JSON有时可以是:

{
"someId": "12345"
}

在这种情况下,您需要解码为String,然后解码为Int64.init

有时JSON可以是:

{
"someId": 12345
}

在这种情况下,对String的解码将失败,您将直接解码为Int64

最新更新