我刚刚开始学习Swift,似乎无法弄清楚如何从Swift中选择一个随机数组而不改变每个点击集中游戏。从本质上讲,我的目标是从字典中选择一个随机值,即一个数组,并将其用于其余的运行。我遇到的问题是,我的随机索引randomThemeIndex
正在改变每次点击,并且不会为游戏中的所有卡保留相同的主题。因此,它从字典中的每个值中选择各种元素,而不仅仅是一个值/数组。以下是我到目前为止的情况:
var themeChoices = ["halloween": ["", "", "", "", "", "", "", "", "", ""],
"animals": ["", "", "", "", "", "", "", "", "", ""],
"faces": ["", "", "", "", "", "", "", "", "", "", ""],
"nature": ["", "", "", "", "", "", "", "", "", "", "❄️", ""],
"food": ["", "", "", "", "", "", "", "", "", "", "", ""],
"sports": ["⚽️", "", "", "", "", "⛳️", "", "", "♀️", "", "️"]]
var emoji = [Int:String]()
func emoji(for card: Card) -> String {
let themeCount = themeChoices.count
let randomThemeIndex = Int(arc4random_uniform(UInt32(themeCount)))
print(randomThemeIndex)
var randomTheme = Array(themeChoices.values)[randomThemeIndex]
if emoji[card.identifier] == nil, randomTheme.count > 0 {
let randomCardIndex = Int(arc4random_uniform(UInt32(randomTheme.count - 1)))
emoji[card.identifier] = randomTheme.remove(at: randomCardIndex)
}
return emoji[card.identifier] ?? "?"
}
答案 0 :(得分:0)
每次拨打emoji(for:)
时都不想选择新的随机数组,对吗?因此,您需要将活动数组索引存储在某处并且每次都使用它。
而不是:
func emoji(for card: Card) -> String {
let themeCount = themeChoices.count
let randomThemeIndex = Int(arc4random_uniform(UInt32(themeCount)))
试试这样:
func emoji(for card: Card, inTheme randomThemeIndex: Int) -> String {
// remove those two lines and keep the rest
现在您需要添加主题索引,因此您不必拨打emoji(for: card)
,而是拨打emoji(for: card, inTheme: themeIndex)
。
您还需要在某处存储主题索引。我不知道你应该在哪里做,因为你的例子中没有足够的代码,但它可能看起来像这样:
lazy var themeIndex: Int = {
let themeCount = themeChoices.count
return Int(arc4random_uniform(UInt32(themeCount)))
}()
然后您可以访问self.themeIndex
。
_(ツ)_ /¯