Alex Stone
Alex Stone

Reputation: 47358

How to store long in a Swift array?

I got a couple user IDs I want to send in an array, but can't figure out the correct Swift 3 syntax for creating an array with very long integers. I tried casting, @ prefix and using as AnyObject, but that did not work.

let idArray = [10211420262370680, 10211420262370680]

Error: integer literal overflows when stored into int

What is the correct way to create an array with such long integers?

Upvotes: 7

Views: 24106

Answers (3)

Solomon Ucko
Solomon Ucko

Reputation: 6109

If you need C interop/FFI, use CLong or CUnsignedLong.

Upvotes: 0

Roi Zakai
Roi Zakai

Reputation: 302

Signed long's array:

let signed64BitIntegerArray: [Int64] =      [-10211420262370680, 10211420262370680]

Unsigned long's array:

let unsigned64BitIntegerArray: [UInt64] =   [ 10211420262370680, 10211420262370680]

Upvotes: 10

Paulo Mattos
Paulo Mattos

Reputation: 19339

Try this instead:

let idArray: [UInt64] = [10_211_420_262_370_680, ...]

As a back of the envelope calculation, every 10 bits buys you 3 decimal digits. For instance, UInt32 maxes out around 4_000_000_000 and so on.

By the way, the underscores _ above are just syntax sugar for big number literals ;-)

Upvotes: 21

Related Questions