Leave a rating/review
Notes: 22. Iterating Collections
Update Notes: The student materials have been reviewed and are updated as of October 2021.
Now, you’ve probably figured out that loops must be useful for more things than just counting up from zero to nine, or printing strings a certain number of times.
And you’re right: loops are really useful for processing data, such as lists of reviews or hour-by-hour weather forecasts.
You’ve already worked with something that stores data in a linear way: arrays! Arrays are ways to store ordered lists of items, and loops are great ways to process that ordered data in an orderly fashion.
In this video, you’ll learn a few ways to process over some arrays of data, and you’ll see how powerful - and useful - loops can be.
Open up the playground page for this video, where I’ve given you some arrays of data. You’ll write a few loops to process this data and do some interesting things with it!
At the top of the playground page, I’ve provided two arrays; one is the day of the week, and the other is a measurement of the temperature of the pool on each of those days.
Now, one of the simplest things you can do with these two arrays is print out the pool temperature for each day, in a nice format.
So since you want to go through, or iterate over, all items in that array, a for loop would be your best choice.
Start by constructing your for loop with for i, for index, from 0 to… what?
for i in 0...
Well, you could define a constant named count up above, and set it to 7, which is the length of each of these arrays.
But if you think back to when you learned about arrays, arrays have a series of properties that give you information about the array. One of those is the count of the items in the array, which you access using the .count property, like so:
for i in 0...daysOfTheWeek.count {
}
Now, you can put a print statement in there to print out the day of the week and the pool temperature in a neat fashion:
for i in 0...daysOfTheWeek.count {
print("\daysOfTheWeek[i]: \poolTemperature[i]")
}
Oh, wait - we have an error in the console. What does it say?
Scroll up a bit, and after the nice tidy list of days and temperatures, you’ll see “Fatal error: Index out of range”.
But you only iterated up to the count of items in the array, right? So why would you get this error?
Remember that an array is zero-indexed, so in an array of seven items, your top index is six. But the count property of dayOfTheWeek gives you…right, seven.
So to fix this, you will need to stop short of seven, and use…right, the half-open range, with the less-than operator:
for i in 0..<daysOfTheWeek.count {
print("\(daysOfTheWeek[i]): \(poolTemperature[i])")
}
That’s better!
Each iteration through the loop, Xcode will print the day of the week, followed by the temperature of that day. This works because both arrays are the same length and are in the same order.
Now, I only like to swim in my pool when the temperature is eighty or above, so I only want to print out the “good” swimming days, WHERE the temperature is eighty or above:
for i in 0..<daysOfTheWeek.count where poolTemperature[i] >= 80 {
print("\(daysOfTheWeek[i]): \(poolTemperature[i])")
}
Hey! Looks like there’s quite a few good swimming days this week.
Now, this first line looks pretty clunky, right here. It would be nicer to write more compact code, since that would be easier for you and someone else reading your code to understand.
So let’s say my friend is planning to visit me and wants to know what my average pool temperature is for the week. To get the average of a set of numbers, you simply add them all together and divide by the count.
So let me set up a sum variable again, and set it to zero:
var sum = 0
If you want to operate on every element of a single array, in this case, poolTemperatures, Swift has a nice shorthand version of a for loop, like this:
for temperature in poolTemperature {
}
You’d read this as “for each temperature in poolTemperature”. temperature will be the value in each element of the array, whereas before you worked with the index and got the element’s value that way.
Now I simply sum each number in the array, like so:
for temperature in poolTemperature {
sum += temperature
}
And then I divide by the count of the elements in the array to find the average temperature:
sum / poolTemperature.count
And the average is 79.
The difference with this for loop is that I don’t need to know the index of each element in the array, or even how many elements there are in the array; I just tell Swift I want to iterate over every element in the array, no matter how many there are.
That’s all I wanted to show you in this video; there are more advanced ways to iterate over collections, but you’ll cover that in later parts of this course!
For now, though I have a short series of challenges for you that will get you comfortable with iterating over collections!