Swift random number [duplicate]

2019-04-26 18:41发布

This question already has an answer here:

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
    }

}

2条回答
一纸荒年 Trace。
2楼-- · 2019-04-26 18:53

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

查看更多
▲ chillily
3楼-- · 2019-04-26 19:08

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)))
查看更多
登录 后发表回答