问题
I'm trying to pull a random item out of an array. When I run, it works about 50/50 between pulling a random item and giving me this error "EXC_BAD_INSTRUCTION". Any idea what's going on?
Right now my code looks like this: BEFORE Solution
func randomCard() -> Card {
let randomIndex = Int(arc4random()) % cardArray.count
let randomCard = cardArray[randomIndex]
cardArray.removeAtIndex(randomIndex)
return randomCard
}
After
func randomCard() -> Card {
let randomIndex = arc4random_uniform(UInt32(cardArray.count))
let randomCard = cardArray[randomIndex.hashValue]
cardArray.removeAtIndex(randomIndex.hashValue)
return randomCard
}
This is what I'm using now and seems to be working.Thanks everyone for the help.
回答1:
arc4random
can return negative numbers which would cause you problems since negative % positive = negative
A better approach would be to use arc4random_uniform
let randomIndex = arc4random_uniform(UInt32(cardArray.count))
EXC_BAD_INSTRUCTION seems like a bad exception to throw on a bounds error, but that does seem to be what you get.
来源:https://stackoverflow.com/questions/24089631/how-to-pull-random-item-out-of-an-array-in-swift