0

I have code that is meant to place a small UIView as a subview at a random X coordinate.

If I place the view at a fixed spot it works but when I calculate the random position my app crashes. Here is the code:

    @IBOutlet var gameView : UIView
    let DROP_SIZE = CGSize(width: 40, height: 40)

    @IBAction func tap(sender : AnyObject) {
        self.drop()
    }

    func drop() {
        var frame = CGRect()
        frame.origin = CGPointZero
        frame.size = DROP_SIZE
        var x = Int(arc4random()) % Int(self.gameView.bounds.size.width) / Int(DROP_SIZE.width)
        frame.origin.x = CGFloat(x) * CGFloat(DROP_SIZE.width)
        var dropView: UIView = UIView(frame: frame)
        dropView.backgroundColor = randomColor()
        self.gameView.addSubview(dropView)

    }

whenever self.drop() is called my app crashes

If I comment out var x & frame.origin.x my app does not crash

So I know the issue is with these two lines of code:

var x = Int(arc4random()) % Int(self.gameView.bounds.size.width) / Int(DROP_SIZE.width)
frame.origin.x = CGFloat(x) * CGFloat(DROP_SIZE.width)

Something about the way these variables are casted is causing the app to crash because if I use a fixed x origin for example frame.origin.x = 100, then the app works as expected.

UPDATE:

because arc4random return UInt32 it will overflow when trying to convert it to an Int

I used this instead

var x = UInt32(arc4random()) % UInt32(self.gameView.bounds.size.width) / UInt32(DROP_SIZE.width)
frame.origin.x = CGFloat(x) * CGFloat(DROP_SIZE.width)
Nearpoint
  • 7,202
  • 13
  • 46
  • 74

1 Answers1

0

because arc4random return UInt32 it will overflow when trying to convert it to an Int

I used this instead

var x = UInt32(arc4random()) % UInt32(self.gameView.bounds.size.width) / UInt32(DROP_SIZE.width)
frame.origin.x = CGFloat(x) * CGFloat(DROP_SIZE.width)

This issue is similar: Crash when casting the result of arc4random() to Int

Community
  • 1
  • 1
Nearpoint
  • 7,202
  • 13
  • 46
  • 74