Search code examples
iosdictionaryswift

How do I get the key at a specific index from a Dictionary in 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. Why not?

var key : String = myDict.keys[0]

Solution

  • 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.