swiftrandomintegernslog

same Int has different values in Swift, mysterious riddle


with this code :

let rand : Int = Int(arc4random())
NSLog("rand = %d %i %@ \(rand)",rand,rand,String(rand))

I get :

rand = -1954814774 -1954814774 2340152522 2340152522

why all 4 values are not the same ?


Solution

  • arc4random generates an unsigned 32bit int. Int is probably 64 bit on your machine so you get the same number and it doesn't overflow. But %i and %d are signed 32-bit format specifiers. See here and here. That's why you get a negative number when arc4random returns a number greater than 2^32-1, aka Int32.max.

    For example, when 2340152522 is generated, you get -1954814774 in the %i position because:

    Int32(bitPattern: 2340152522) == -1954814774
    

    On the other hand, converting an Int to String won't change the number. Int is a signed 64 bit integer.