如何从Swift的Dictionary中的特定索引获取密钥? [英] How do I get the key at a specific index from a Dictionary in Swift?
问题描述
我在Swift中有一个字典
,我想在特定索引中获取密钥。
I have a Dictionary
in Swift and I would like to get a key at a specific index.
var myDict : Dictionary<String,MyClass> = Dictionary<String,MyClass>()
我知道我可以迭代键并记录它们
I know that I can iterate over the keys and log them
for key in myDict.keys{
NSLog("key = \(key)")
}
然而,奇怪的是,这样的东西是不可能的
However, strangely enough, something like this is not possible
var key : String = myDict.keys[0]
为什么?
推荐答案
这是因为键
返回 LazyMapCollection& [Key:Value],Key>
,不能用Int进行下标。一种处理这种情况的方法是通过您要下标的整数来推进字典的 startIndex
,例如:
That's because keys
returns LazyMapCollection<[Key : Value], Key>
, which is can't be subscripted with an Int. One way to handle this is to advance the dictionary's startIndex
, by the integer that you wanted to subscript by, for example:
let intIndex = 1 // where intIndex < myDictionary.count
let index = myDictionary.startIndex.advancedBy(intIndex) // index 1
myDictionary.keys[index]
另一种可能的解决方案是将键
作为输入初始化一个数组,然后可以对结果使用整数下标: / p>
Another possible solution, would be to initialize an array with keys
as input, then you can use integer subscripts on the result:
let firstKey = Array(myDictionary.keys)[0] // or .first
请记住,字典本来是无序的,所以不要指望给定索引的键总是一样的。
Remember, dictionaries are inherently unordered, so don't expect the key at a given index to always be the same.
这篇关于如何从Swift的Dictionary中的特定索引获取密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!