Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer literal overflows when stored into 'Int'

Tags:

swift

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".

like image 840
dennis-tra Avatar asked Feb 11 '16 01:02

dennis-tra


2 Answers

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
like image 77
vacawama Avatar answered Oct 19 '22 01:10

vacawama


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.

like image 44
emrepun Avatar answered Oct 18 '22 23:10

emrepun