我要做的是生成1到52之间的随机数(firstRandomNumber
),然后将dictionaryTest
设置为等于字典中相应索引处的键。
例如,如果生成的firstRandomNumber
恰好是2
,则dictionaryTest
应该等于deckDictionary[2]
处的密钥,即"card2"
。< / p>
var deckDictionary = [
"card1": ["rank","suit"],
"card2": ["rank","suit"],
"card3": ["rank","suit"],
"card4": ["rank","suit"],
"card5": ["rank","suit"],
////... clipped for brevity
"card52": ["rank","suit"],
]
let firstRandomNumber = Int(arc4random_uniform(52))+1
let dictionaryTest = deckDictionary[firstRandomNumber]
print(dictionaryTest)
但是当我尝试这样做时,设置dictionaryTest
会给我以下错误:
无法使用“Int”类型的索引下标“[String:Array]”类型的值
我不确定这意味着什么,是因为“card2”键/字符串本身包含一个数组?
答案 0 :(得分:2)
那是因为你的deckDictionary中的键是String类型的,你试图使用int键访问deckDictionary中的元素。 你可以做这样的事情:
let firstRandomNumber = Int(arc4random_uniform(52))+1
let key = "card\(firstRandomNumber)"
let dictionaryTest = deckDictionary[key]