Search code examples
iosswiftexc-bad-instruction

How to pull random item out of an array in Swift?


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.


Solution

  • 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.