参见英文答案 >
Crash when casting the result of arc4random() to Int7个
我有这个drawRandomCard函数的问题.
我有这个drawRandomCard函数的问题.
它的工作方式就像它应该使用一段时间,但最终它崩溃了应用程序.
这是代码:
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 } }
使用arc4random_uniform避免模偏差.如下:
原文链接:https://www.f2er.com/swift/319340.htmllet randomNumber = arc4random_uniform(150)
对于您的示例,它将是:
let randomNumber = Int(arc4random_uniform(UInt32(cardDeck.count)))