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

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


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


Swift 3 : Array() can be useful to do this .

Get Key :

let index = 5 // Int ValueArray(myDict)[index].key

Get Value :

Array(myDict)[index].value


Here is a small extension for accessing keys and values in dictionary by index:

extension Dictionary {    subscript(i: Int) -> (key: Key, value: Value) {        return self[index(startIndex, offsetBy: i)]    }}