EXC_BREAKPOINT fast access triggers
Here is my code (largeAsteroids.count is never 0):
var largeAsteroids=[[SKTexture]]()
func randomLargeAsteroidTextures()->Array<SKTexture>{
let i=Int(arc4random())%largeAsteroids.count
return largeAsteroids[i]// this line triggers EXC_BREAKPOINT
}
When I execute my code, I don't get any errors, but I get EXC_BREAKPOINT. I ensured there was no breakpoint and at the index I was a valid object.
I first changed SKTexture to AnyObject, it didn't help. Then I tried to use NSMutableArray instead of swift array, the problem still exists:
var largeAsteroids=NSMutableArray()
func randomLargeAsteroidTextures()->AnyObject{
let i=Int(arc4random())%largeAsteroids.count
return largeAsteroids.objectAtIndex(i) // this line triggers EXC_BREAKPOINT
}
update:
Problem solved, replace:
let i=Int(arc4random())%largeAsteroids.count
by:
let i=Int(arc4random_uniform(UInt32(largeAsteroids.count)))
Thanks for the solution Matt:
You should probably use arc4random_uniform. You will get a modular deviation from the current implementation. - Matt Gibson
source to share
You had a 32-bit target, right? On a 32-bit target (like iPhone 4) Swift Ints are 32-bit and signed. However, on any platform, arc4random () returns an unsigned 32-bit integer.
Due to this conflict and your conversion to Int, Int(arc4random())
sometimes - in fact, half the time, all other things being equal - your number was negative, giving you a negative array index and causing the problem (although I get EXC_BAD_INSTRUCTION as I expected, when i reproduce the problem, presumably you have an exception breakpoint?)
My suggestion to use arc4random_uniform should work fine until your asteroid count is greater than Int.max on a 32-bit platform, which is probably unlikely unless you give the player a really hard time. This will also avoid modulo bias in the random generation, so the random numbers you get will be more evenly distributed than in your original solution.
source to share