我有以下数组:
var deckArray = [
"card1": ["rank","suit"],
"card2": ["rank","suit"],
"card3": ["rank","suit"],
"card4": ["rank","suit"],
"card5": ["rank","suit"],
"card6": ["rank","suit"],
"card7": ["rank","suit"],
]
为了简洁起见,我剪切了数组的其余部分,但整个事物包含52个对象。我想要做的是从1到52中选择一个随机数,并将firstCardString
属性设置为等于数组中与该索引相对应的任何键。
例如,如果它生成的随机数为5
,则会将firstCardString
设置为等于card5
。
我试图这样做:
let firstRandomNumber = Int(arc4random_uniform(52))
let firstCardString:String = self.deckArray[firstRandomNumber]
但我收到以下错误:
无法下标类型' [String:Array]'索引类型为' Int'
这没有意义,因为firstCardString:string
明确是string
类型,而不是int。
答案 0 :(得分:2)
您已将deckArray声明为字典。所以你需要传递一个String(键)而不是一个Int
let firstRandomNumber = Int(arc4random_uniform(52))+1
let firstCardString = deckArray["card\(firstRandomNumber)"]