Iteration and Enumeration

Iteration over arrays is quite straightforward because an array is already a sequence. Thus, we can directly iterate over arrays:

for <identifier> in <array> {
    <instructions to execute>

Sometimes though, you may want to iterate over the element as well as their respective locations in the array. This is achievable in two ways. The naive method would be to iterate in a range from 0 to the length you are iterating to. This would allow you to bind the index to your identifier and then you can just get the element at the corresponding location through subscripting. The better method would be to use enumeration. All arrays have an enumerated() method, which returns an EnumeratedSequence. Forgetting the jargon (I'm sure there's a lot of excessive type aliasing going on) enumerated converts your array into another array of tuples containing the indices and elements respectively. Basically, think of enumerated as having the type: [Element] -> [(Int, Element)].

let myStrings = ["a", "b", "c"]
for (index, i) in myStrings.enumerated() {
    print(index, i)
// 0 a
// 1 b
// 2 c

You'll notice I use a funky identifier there (index, i). Tuples allow us to assign multiple values at once. The nth element of the tuple is assigned to the nth element of the tuple of identifiers.

Last updated