2

I have some JSON Dictionary that looks like this:

{
biography = "";
externalUrl = "";
followersCount = 467;
followingsCount = 428;
fullName = dima;
hasAnonymousProfilePicture = 1;
id = 2673580202;
isBusiness = 0;
isPrivate = 0;
mediaCount = 0;
picture = "http://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg";
username = "kmr.dma";
}

So I'm parsing 'id' parameter like this:

guard let userID = array["id"] as? Int else {
   return
}

And I'm getting the value like : -1621387094
Thats because Int.max() is 2147483647 and my id is 2673580202

So the problem is clear but how to get over it ?

2 Answers2

3

Int can be a 32-bit or 64-bit integer, depending on the platform. As already said in the comments, you need Int64 or UInt64 to store a value > 2147483647 on all platforms.

You cannot cast from AnyObject to Int64 directly, therefore the conversion is via NSNumber:

guard let userId = (dict["id"] as? NSNumber)?.longLongValue  else { return }

For Swift 3, replace longLongValue by int64Value.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
-1

Try to parse it as Double. Double is much bigger than Int.

Example:

guard let userID = array["id"] as? Double else {
    return
}
firstinq
  • 772
  • 6
  • 13
Max Pevsner
  • 4,098
  • 2
  • 18
  • 32
  • 3
    Parsing an id as a `Double` is a terrible idea. Rounding could make two different ids equal... It should be parsed as a `String` if `Int64` is not enough. – deadbeef Aug 23 '16 at 18:40
  • `Double` isn't "much bigger" than `Int`. They're both `8` bytes. `Double`'s range is much bigger, but that's because it trades precision for range. – Alexander Aug 23 '16 at 18:40
  • @deadbeef, if you pay attention to the JSON, you will notice that id is not defined as `String`. I assumed, OP cant change the JSON format. – Max Pevsner Aug 23 '16 at 18:46
  • @AlexanderMomchliov: `Int` can be 32-bit or 64-bit, depending on the platform. In this case it is apparently 32-bit. `Double` has a 54(?) bit mantissa, so it is exact up to 2^54. That is better than a 32-bit Int, but worse than a 64-bit Int. – Martin R Aug 23 '16 at 18:46
  • @MartinR I know, but I'm not sure where you're going with that – Alexander Aug 23 '16 at 19:52
  • @AlexanderMomchliov: It was just a response to your claim that Int is 8 bytes, which is not true in general. – Martin R Aug 23 '16 at 19:57
  • Ah yes, I misspoke. I only develop for 64 bit macs. I meant `Int64` – Alexander Aug 23 '16 at 20:01