Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this Int64 Swift Decoding superfluous?

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?

like image 243
Isaaс Weisberg Avatar asked May 29 '26 18:05

Isaaс Weisberg


1 Answers

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.

like image 84
Sweeper Avatar answered May 31 '26 15:05

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!