0

I have a problem with one of my function: my application run perfectly on iPhone 5s, 6, etc, but on a iPhone 5 I have a problem with my code. When my function is called, I always have this problem:

switch choixDeCote {

        case 1 : //Haut
            let MinValue = self.size.width / 8
            let MaxValue = self.size.width - 200
            SpawnX = UInt32(MaxValue - MinValue)
            SpawnX = arc4random_uniform(SpawnX)
            SpawnY = UInt32(self.size.height)
            directionX = Int(arc4random()) % Int(self.frame.size.width)
            print(directionX)
            directionY = 0
            action = SKAction.moveTo(CGPoint(x: CGFloat(directionX),y: CGFloat(directionY)),duration: 4)
            break

And Xcode says that directionX = Int(arc4random()) % Int(self.frame.size.width) has a problem, but I don't know which one.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Mathis Delaunay
  • 172
  • 1
  • 16

1 Answers1

1

arc4random() returns a UInt32. On a 32-bit machine like the iPhone 5, this can overflow an Int.

I would suggest instead:

directionX = Int(Int32(bitPattern: arc4random_uniform(UInt32(self.frame.size.width))))

the Int32(bitPattern:) is only a precaution and isn't really necessary since the self.frame.size.width is much smaller than MAXINT32 so the random number generated won't overflow an Int. You can just do:

directionX = Int(arc4random_uniform(UInt32(self.frame.size.width)))
vacawama
  • 150,663
  • 30
  • 266
  • 294