Swift random number [duplicate]

那年仲夏 提交于 2020-01-13 09:02:51

问题


I'm having problems with this drawRandomCard function.

It works just like it should for some time, but eventually it crashes the application.

Here is the code:

import Foundation


var cardDeck = Array<PlayingCard>()

class Deck {

    func addCard(card : PlayingCard , atTop : Bool = false){

        if atTop {
            cardDeck.insert(card, atIndex: 0);
        }else{
            cardDeck += card
        }
    }

    func drawRandomCard() -> PlayingCard{
        var card = PlayingCard()
        var randomNumber : Int = Int(arc4random()) % (cardDeck.count - 1)
        card = cardDeck[randomNumber]
        cardDeck.removeAtIndex(randomNumber)
        return card
    }

}

回答1:


Use arc4random_uniform to avoid modulo bias. Like following:

let randomNumber = arc4random_uniform(150)

For your example, it will be:

let randomNumber = Int(arc4random_uniform(UInt32(cardDeck.count)))



回答2:


Try this: Int(rand()) instead of arc4random()



来源:https://stackoverflow.com/questions/24119714/swift-random-number

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