如何设置变量的值(字符串)等于在数组中的键? [英] How to set a variable's value (string) to be equal to a key in an array?
问题描述
我有以下数组:
VAR deckArray = [
卡1:[等级,西服],
卡2:等级,西服],
card3:等级,西服],
card4:等级,西服],
card5:等级,西服],
CARD6:等级,西服],
card7:等级,西服],
]
我夹住阵列出于简洁的其余部分,而是整个东西包含52的对象。我想要做的就是选择一个随机数从1到52,并设置 firstCardString
属性等于任何键对应的数组中的索引。
例如,如果它产生的随机数 5
,它会设置 firstCardString
等于 card5
。
我试图做到这一点,像这样:
让firstRandomNumber = INT(arc4random_uniform(52))
让firstCardString:字符串= self.deckArray [firstRandomNumber]
但我发现了以下错误:
无法下标类型的值'[字符串:数组]与类型的索引,诠释
块引用>这是没有意义的,因为
firstCardString:字符串
是明确类型的字符串
,不是int <。 / p>解决方案您已经声明的deckArray作为解释。所以,你需要传递一个String(键)不是int
让firstRandomNumber = INT(arc4random_uniform(52))+ 1
让firstCardString = deckArray [牌\\(firstRandomNumber)]I have the following array:
var deckArray = [ "card1": ["rank","suit"], "card2": ["rank","suit"], "card3": ["rank","suit"], "card4": ["rank","suit"], "card5": ["rank","suit"], "card6": ["rank","suit"], "card7": ["rank","suit"], ]
I clipped the rest of the array for brevity, but the entire thing contains 52 objects. What I want to do is pick a random number from 1 to 52, and set the
firstCardString
property to be equal to whichever key corresponds to that index in the array.For example, if the random number it generates is
5
, it would setfirstCardString
to be equal tocard5
.I've tried to do it like so:
let firstRandomNumber = Int(arc4random_uniform(52)) let firstCardString:String = self.deckArray[firstRandomNumber]
But I'm getting the following error:
Cannot subscript a value of type '[String : Array]' with an index of type 'Int'
This doesn't make sense, because
firstCardString:string
is explicitly of typestring
, not int.解决方案You have declared your deckArray as a Dictionary. So you need to pass a String (key) not an Int
let firstRandomNumber = Int(arc4random_uniform(52))+1 let firstCardString = deckArray["card\(firstRandomNumber)"]
这篇关于如何设置变量的值(字符串)等于在数组中的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!