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 = ["Marinos", "Stuart", "Thomas", "Kirsty", "Carlos"] for mate in classMates { print("\(mate)") }
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("\(i + 1). \(name)") }
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 = ["Marinos": 60, "Stuart": 65, "Thomas": 70, "Kirsty": 65, "Carlos":60] for (name, mark) in studentsAndMarks { print("\(name) - \(mark)") }
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("\(i). \(name) - \(mark)") }
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) let matesGrades = Array(studentsAndMarks.values)
Last type is the Set. The story is repeated. Use for-in and that’s all.
var starWarsPlanets: Set = ["Naboo", "Tatooine", "Mustafar", "Coruscant"] for planet in starWarsPlanets { print("\(planet)") }
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("\(planet)") }
with output:
Coruscant
Mustafar
Naboo
Tatooine
Last but not least, if you want to download the playground file follow that link!