我正在开发扑克应用程序。我有两个问题,,,
1)刚刚开始研究DeckOfCards类来处理套牌。我在其中一个for循环中不断收到错误(“预期声明”)。它适用于游乐场但不适用于项目(不过作为课程)。我该如何解决这个问题?
2)用这种方式表示卡片是否可以(数组中有2个字符串)?
导入基金会
class DeckOfCards {
var newDeck = ["A♠️", "2♠️", "3♠️", "4♠️", "5♠️",...."K♠️",
"A♥️", "2♥️", "3♥️", "4♥️", "5♥️",...."K♥️",
"A♣️", "2♣️", "3♣️", "4♣️", "5♣️",...."K♣️",
"A♦️", "2♦️", "3♦️", "4♦️", "5♦️",...."K♦️"]
var deck = [String]()
var randomNumber = 0
init() {
deck = []
}
for _ in 1...52 { // ERROR ON THIS LINE ("Expected Declaration")
randomNumber = Int(arc4random_uniform(UInt32(newDeck.count)))
deck.append(newDeck.removeAtIndex(randomNumber))
}
}
答案 0 :(得分:1)
这是因为你不能在类定义中像这样挂起代码。你需要把它放在func
中。 e.g。
func shuffleDeck() -> [String] {
var deck = [String]()
for _ in 1...52 {
randomNumber = Int(arc4random_uniform(UInt32(newDeck.count)))
deck.append(newDeck.removeAtIndex(randomNumber))
}
return deck
}
要回答问题的第二部分,最好使用enum
代表卡片。这是一个很好的例子:Add a method to Card that creates a full deck of cards, with one card of each combination of rank and suit