That exception happens because arc4random()
returns UInt32
and you are subtracting a value of that, which possibly causes a negative value, which is not representable as an unsigned integer.
To fix this you may want to cast the expression to Int32 before subtracting:
var y = CGFloat(self.size.height / 3) + CGFloat((Int32)(arc4random() % 100) - 50)
Regarding the x
value above - you create CGFloat
and only subtract after that and therefore not encounter the above situation. Therefore a different fix would be the following
var y = CGFloat(self.size.height / 3) + CGFloat(arc4random() % 100) - 50
You basically have to ensure that at the point where you subtract something you have no unsigned type present.
The annoying thing about this is that the compiler does not warn you and the code actually works sometimes, every time when arc4random
returns something larger than 50 and will therefore not drift into the negative values...
Incorporating the feedback and suggestion that you should not use arc4random % something
the best solution would be to use arc4random_uniform
.
arc4random % something
will not yield a proper distribution of the random values, while arc4random_uniform(something)
does - this has already been discussed on SO before.
A final note: you probably should choose 101 as upper bound instead of 100 because both arc4random
as well as arc4random_uniform
produce a value between 0 and (upper-1), e.g. 0 and 99. If you subtract 50 you get a value between -50 and +49. Choosing 101 will yield the desired range of -50 to +50.
var y = CGFloat(self.size.height / 3) + CGFloat(arc4random_uniform(101)) - 50