I have seen a piece of code online which uses Swift Codable do decode a JSON into a 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)
}
}
This code:
- decodes a string
- tries to parse it into
Int64 - if it fails - it directly attempts to decode an
Int64
My question is - is this code superfluous?
Is there any scenario where Int64.init(_:) from String would be able to decode something that JSONDecoder.decode wouldn't?
And actually, isn't this "decode String - init Int64" the exact same thing that JSONDecoder does under the hood?