Iterating through Collection Types in Swift

Collection types in swift are the arrays, the dictionaries and the sets. Iterating through them is really easy using the for-in loop. The purpose of this article is to gather all the related information in one point, neat?

Lets start with the arrays. We have an array of Strings and we want to print the contents, each name in a new line.

let classMates = [&quot;Marinos&quot;, &quot;Stuart&quot;, &quot;Thomas&quot;, &quot;Kirsty&quot;, &quot;Carlos&quot;]

for mate in classMates {
print(&quot;\(mate)&quot;)
}


The output will be:
Marinos Stuart Thomas Kirsty Carlos

A for-in loop with a print using string interpolation will do the job.

What if we want to include an index in front. Don’t think of something complex, the solution is enumerate(). This function return a tuple containing the index (starts from zero) and the array item. So it will looks like:

for (i, name) in classMates.enumerate() {
print(&quot;\(i + 1). \(name)&quot;)
}


and the output will be:
1. Marinos 2. Stuart 3. Thomas 4. Kirsty 5. Carlos

Next type is Dictionary. The story is almost the same. We will use for-in and tuples.

let studentsAndMarks = [&quot;Marinos&quot;: 60, &quot;Stuart&quot;: 65, &quot;Thomas&quot;: 70, &quot;Kirsty&quot;: 65, &quot;Carlos&quot;:60]

for (name, mark) in studentsAndMarks {
print(&quot;\(name) - \(mark)&quot;)
}


with output:
Kirsty - 65 Thomas - 70 Carlos - 60 Stuart - 65 Marinos - 60

Do you want an index in front? You know the tip.

for (i, (name, mark)) in studentsAndMarks.enumerate() {
print(&quot;\(i). \(name) - \(mark)&quot;)
}


and the output will be:
0. Kirsty - 65 1. Thomas - 70 2. Carlos - 60 3. Stuart - 65 4. Marinos - 60

Don’t forget that if you want to get the array of keys or values from the dictionary is dead easy. Use the following;

let matesNames = Array(studentsAndMarks.keys)


Last type is the Set. The story is repeated. Use for-in and that’s all.

var starWarsPlanets: Set = [&quot;Naboo&quot;, &quot;Tatooine&quot;, &quot;Mustafar&quot;, &quot;Coruscant&quot;]

for planet in starWarsPlanets {
print(&quot;\(planet)&quot;)
}


and the output will be:
Naboo Tatooine Mustafar Coruscant

Yes, I know that you are a demanding reader. Although set is an unordered collection type you want to print the results in alphabetic order. Ok then you should use sort()

for planet in starWarsPlanets.sort() {
print(&quot;\(planet)&quot;)
}


with output:
Coruscant Mustafar Naboo Tatooine