the_critic the_critic - 3 months ago 14x
iOS Question

How do I get the key at a specific index from a Dictionary in Swift?

I have a

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]

Why ?


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

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.