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

二次信任 提交于 2019-12-07 18:32:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!