1

I'm having a really weird issue with Swift/Xcode (not really sure where the source lies, to be honest).

I have to following code:

extension Int {
    func random(min : Int = 0, max : Int = Int(UInt32.max - 1)) {
        return min + Int(arc4random_uniform(UInt32(max - min + 1)))
    }
}

When I build this code in Xcode, it works perfectly fine. When I try to build it using xcodebuild though, the compiler gives me the following error:

integer overflows when converted from 'UInt32' to 'Int'

    public static func random(min : Int = 0, max : Int = Int(UInt32.max - 1)) -> Int {

Which is weird, since the values of Int.max and UInt32.max are no where close.

I'm using Xcode 7.0 beta 5 for compilation if it is any help...'cause I'm absolutely stumped.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Ramon Kleiss
  • 1,684
  • 15
  • 25

1 Answers1

3

That error occurs if you compile for a 32-bit device (e.g. iPhone 5), because Int is then a signed 32-bit integer, and UInt32.max - 1 outside of its range.

Another problem is the calculation of UInt32(max - min + 1), which can crash at runtime due to an overflow, e.g. if you call

random(min : Int.min, max : Int.max)

See How can I generate large, ranged random numbers in Swift? for a possible solution to avoid overflows when generating random numbers for arbitrary ranges.

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