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 ?
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.
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.
In dictionary, keys are unordered.
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 ( [:] ).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With