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:
Int64Int64My 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?
It is not superfluous. It could be used to handle JSON that sometimes has numbers encoded as a string (within quotes), and sometimes just as a number.
For example, the JSON could sometimes be:
{
"someId": "12345"
}
in which case you need to decode to String, and then Int64.init
And sometimes the JSON could be:
{
"someId": 12345
}
in which case decoding to String would fail, and you would directly decode to Int64.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With