我尝试了以下简单的卡示例,但在尝试访问Array属性时一直出错。特别是在func中,getRandomCard()卡在单击“翻转”按钮后变得无法访问。行为不一致,有时在第一次单击按钮时会发生错误,而在其他时候可以在错误发生前几次单击按钮。我究竟做错了什么?感谢您的任何见解。
//Class PlayingCardDeck
import Foundation
let validSuits = ["♣️", "♦️", "♥️", "♠️"]
let maxRank = 13
class PlayingCardDeck {
var cards: [PlayingCard] = []
init() {
for suit in validSuits {
for rank in 1...maxRank {
var card = PlayingCard()
card.suit = suit
card.rank = rank
self.addCard(card)
}
}
}
func addCard(aCard: PlayingCard) {
cards.append(aCard)
}
func getRandomCard() -> PlayingCard {
let idx = Int(arc4random()) % cards.count
let retCard = cards[idx]
cards.removeAtIndex(idx)
return retCard
}
}
//Class PlayingCard
import Foundation
let rankStrings = ["?", "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
class PlayingCard {
var suit = "?"
var rank = 0
var contents: String {
get {
return rankStrings[rank] + suit
}
}
}
//Class ViewController
import UIKit
class ViewController: UIViewController {
var myDeck = PlayingCardDeck()
@IBOutlet weak var cardLabel: UILabel!
@IBAction func flipButton(sender: UIButton) {
let s = myDeck.getRandomCard().contents
cardLabel.text = s
}
}
答案 0 :(得分:0)
我敢打赌,尽管有错误消息,但您实际上看到了整数溢出错误。请尝试使用arc4random_uniform()
:
let idx = Int(arc4random_uniform(UInt32(cards.count)))