dennis-tra
dennis-tra

Reputation: 1319

Integer literal overflows when stored into 'Int'

Xcode is complaining about the following line:

let primary = UInt32(0x8BC34AFF)

With this error message:

Integer literal '2344831743' overflows when stored into 'Int'

I see that it overflows a signed integer, but I intentionally used UInt32. My question is more "how can this be" instead of "how can I fix it".

Upvotes: 20

Views: 12381

Answers (2)

emrepun
emrepun

Reputation: 2666

You may also run into this issue if you have not selected any device or simulator before trying to run unit tests. (in that case default Generic iOS Device is selected). I have received this error for some integer values in unit test classes.

Upvotes: 1

vacawama
vacawama

Reputation: 154613

UInt32(0x8BC34AFF) creates a UInt32 by calling an initializer. The UInt32 initializer you are calling is:

init(_ v: Int)

The problem is that on a 32-bit device (iPhone5 and earlier), type Int is 32-bits. So, the constant you are passing 0x8BC34AFF overflows the Int that you are passing to the initializer of UInt32.

The way to have this work on both 32-bit and 64-bit devices is to cast the integer literal to the type:

let primary = 0x8BC34AFF as UInt32

Alternatively, declare the variable to be UInt32 and just assign the constant:

let primary:UInt32 = 0x8BC34AFF

Upvotes: 32

Related Questions