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

the_critic picture the_critic · Jul 8, 2014 · Viewed 148.2k times · Source

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]

Why ?

Answer

Mick MacCallum picture Mick MacCallum · Jul 8, 2014

That's because keys returns LazyMapCollection<[Key : Value], Key>, which 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.index(myDictionary.startIndex, offsetBy: intIndex)
myDictionary.keys[index]

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.