Home > Back-end >  Is this Int64 Swift Decoding superfluous?
Is this Int64 Swift Decoding superfluous?

Time:09-13

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?

CodePudding user response:

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.

  • Related