How do I iterate through a dictionary using an index?

How do I enumerate through a dictionary using an index? I need to get an item from the dictionary each time I call a method, as in my pseudocode below:


n = 0

func do() {
   
     get the nth item in dictionary

     n += 1

}


Or if possible do this:


var item

func co() {

     self.item = next item in dictionary

}
Answered by QuinceyMorris in 285477022

Study this code in a playground:


let dict = ["A": 1, "B": 2, "C": 3]
var i = dict.startIndex

print (dict [i])
i = dict.index (after: i)
print (dict [i])
i = dict.index (after: i)
print (dict [i])


That's one way of approaching what you want.

Accepted Answer

Study this code in a playground:


let dict = ["A": 1, "B": 2, "C": 3]
var i = dict.startIndex

print (dict [i])
i = dict.index (after: i)
print (dict [i])
i = dict.index (after: i)
print (dict [i])


That's one way of approaching what you want.

Take care, as dictionary are unordered, getting the nth does not really make sense. You can iterate as Quincey explained, but the order may change !


Have a look here for examples : h ttps://stackoverflow.com/questions/29601394/swift-stored-values-order-is-completely-changed-in-dictionary

The order is stable enough (in the obvious ways) to iterate over, repeatedly. From the Dictionary documentation (https://developer.apple.com/documentation/swift/dictionary):


"The order of key-value pairs in a dictionary is stable between mutations but is otherwise unpredictable. […] A dictionary’s indices stay valid across additions to the dictionary as long as the dictionary has enough capacity to store the added values without allocating more buffer. When a dictionary outgrows its buffer, existing indices may be invalidated without any notification."


If you don't care which entry you get, each time you ask for one, or if you're just getting them all and the order doesn't matter, then iterating over the index is fine. If you want to randomize the retrievals, it's harder because you want the order to "feel" random, i.e. unpredictable.


The SO post you reference is on a slightly different topic: why the index order is different from the source literal order. That's because the index order represents (directly or indirectly) the order in which entries are stored, and a primary determinant on that is (likely to be) the hashValue of the keys.

Did you have an example of your dictionary/data and how you want the output to look?


From the docs/Swift


"You can search a dictionary’s contents for a particular value using the

contains(where:)
or
index(where:)
methods supplied by default implementation. The following example checks to see if
imagePaths
contains any paths in the
"/glyphs"
directory:"


let glyphIndex = imagePaths.index { $0.value.hasPrefix("/glyphs") }
if let index = glyphIndex {
    print("The '\(imagesPaths[index].key)' image is a glyph.")
} else {
    print("No glyphs found!")
}
// Prints "The 'star' image is a glyph.")
How do I iterate through a dictionary using an index?
 
 
Q