bignerdranch / Freddy

A reusable framework for parsing JSON in Swift.
MIT License
1.09k stars 120 forks source link

Large(64 bit) integers #235

Closed Jake6329 closed 7 years ago

Jake6329 commented 7 years ago

In terms of 64 bit integers, I found a 'strange' behavior of Freddy. Here's my test code:

    do { // big integer test
        let str = "{\"value\": 1467675897415}"
        let data = str.data(using: .utf8)
        let jsonObj = try JSON(data: data!)
        let value = try jsonObj.getInt(at: "value") // getting big integer as Int causes error
        print("int value: \(value)")
    } catch {
        print("error: \(error)")
    }
    do { // small integer test
        let str = "{\"value\": 1467}"
        let data = str.data(using: .utf8)
        let jsonObj = try JSON(data: data!)
        let value = try jsonObj.getInt(at: "value") // getting small integer as Int works fine
        print("int value: \(value)")
    } catch {
        print("error: \(error)")
    }
    do { // big integer as string test
        let str = "{\"value\": 1467675897415}"
        let data = str.data(using: .utf8)
        let jsonObj = try JSON(data: data!)
        let value = try jsonObj.getString(at: "value") // getting big integer as String worked unexpectedly
        print("string value: \(value)")
    } catch {
        print("error: \(error)")
    }

And I get this result:

error: valueNotConvertible(1467675897415, Swift.Int)
int value: 1467
string value: 1467675897415

It seems that Freddy parses big integers as Strings, and I guess it might have to do something with the old 32bit iOS hardwares. Any suggestion on how to deal with integer sizes?

[UPDATE] Actually, I was running the test code in the 32bit hardware simulator. When I ran it later with the latest hardware simulator(iPad Pro), Freddy did parse the big integer as Int and there was no error. It still raises a question though. How do I manage to work with both 32 and 64 bit platforms? I wish there were something like getInt64() method for the cases where I'm sure that the value is in the range of 64 bit integers.

jgallagher commented 7 years ago

This is intentional if the value doesn't fit into Swift's Int (which as you mention in your update, it doesn't on a 32-bit device). There is some background/rationale in the discussion on #76.

I could see an argument for something like a getInt64(). For now, though, your current options are: