Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

var key : String = myDict.keys[0] 

Why ?

like image 559
the_critic Avatar asked Jul 08 '14 20:07

the_critic


People also ask

How do you access an index from a dictionary?

You can find a dict index by counting into the dict. keys() with a loop. If you use the enumerate() function, it will generate the index values automatically.

How do you check if a key exists in a dictionary Swift?

Swift – Check if Specific Key is Present in Dictionary To check if a specific key is present in a Swift dictionary, check if the corresponding value is nil or not. If myDictionary[key] != nil returns true, the key is present in this dictionary, else the key is not there.

Are Keys in dictionary indexed?

In dictionary, keys are unordered.

Which type is defined for key in dictionary in Swift?

The Key type of the dictionary is Int , and the Value type of the dictionary is String . To create a dictionary with no key-value pairs, use an empty dictionary literal ( [:] ).


1 Answers

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.

like image 119
Mick MacCallum Avatar answered Sep 28 '22 23:09

Mick MacCallum