For-In Loops
đŻ Learning Goals
- Explain the concept of iteration
- Write a for-in loop to accomplish repetitive code
- Use for-in loops to iterate over arrays and dictionaries
đ Technical Vocabulary
- Array
- Dictionary
- Element
- Index
- Iterate
- Loop
đ Warm Up
Iteration (or looping for a specified number of times) is a process of repeating a task for each object in a collection. For each of the scenarios below, weâll walk through using examples we are familiar with to demonstrate the concept.
These are examples that would be programmatically challenging because they would require several steps, but are things that we do every day.
Scenario | Collection | For each... | Do this: | Then: |
---|---|---|---|---|
Grading papers | papers | paper |
|
repeat with next paper |
Feeding animals | animals | animal |
|
repeat with next animal |
We can also iterate in programming. By âin programming,â we mean things that could be done, with relative ease, by a computer like crunching numbers.
Scenario | Collection | For each... | Do this: | Then: |
---|---|---|---|---|
Calculating max heart rate | birth years | year |
|
repeat with next year |
Formatting names | names | name |
|
repeat with next name |
Think About It: Iteration in Real Life and Programming
Brainstorm a real life scenario that uses iteration. Fill out the table below and be ready to share.
Scenario | Collection | For each... | Do this: | Then: |
---|---|---|---|---|
Think of how arrays are used in apps that you use. Why might you a developer to iterate over that collection? Jot down your scenario below.
Scenario | Collection | For each... | Do this: | Then: |
---|---|---|---|---|
What is a for-in
loop?
A for-in
loop is a block that will run code a specific number of times. It can iterate through a collection (array or dictionary) and do something with each element. Loops are very common and necessary parts of a programming language; every programming language has its own version of getting this done.
The benefit of loops is they save us time. When we want to do to the same thing for a lot of items, we only have to write that command once. For example, if we wanted to do something with each string in the trending
array, our code would look like this:
var trending = ["@cosette", "@avani", "@lorengray", "@jamescharles"]
print("Have you seen that TikTok from /(trending[0]) yet?!");
print("Have you seen that TikTok from /(trending[1]) yet?!");
print("Have you seen that TikTok from /(trending[2]) yet?!");
print("Have you seen that TikTok from /(trending[3]) yet?!");
Right now, this doesnât seem so bad. What if we had 100 creators on our list? 1000? Thatâs a lot of lines of code to write and potentially a lot of places we would need to update it every time we added or removed a creator.
Syntax (Arrays)
We can use for-in
loops to do something with each individual element from an array. If we use our array of trending TikTok creators, we could write a for-in
loop to do the same thing with each of the string elements.
var trendingCreators = ["@cosette", "@avani", "@lorengray", "@jamescharles"]
for creator in trendingCreators {
print(creator)
}
Think About It
- What do you think will happen when we run the code above?
- What if we add another creator to our array?
- Why do you think we used the words "creator" and "trendingCreators" in our
for-in
loop?
Breaking it Down
Letâs try to understand whatâs going on here.
var trendingCreators = ["@cosette", "@avani", "@lorengray", "@jamescharles"]
for creator in trendingCreators {
print(creator)
}
// => @cosette
// => @avani
// => @lorengray
// => @jamescharles
The word creator
right after the keyword for
refers to each element of our array, and the trendingCreators
after the in
keyword is the name of the array we are telling the computer to iterate over. Weâve told our loop to run the same number of times as there are elements in the array. So, since we currently have 4 elements in the array, it will run 4 times. If we added another creator to our array, the loop would run 5 times.
By using the word creator
after the for
keyword, weâre telling our code that we can use creator
like a variable (only inside of the code block, or the curly braces), and its value for each iteration of the loop will be whatever element of the array itâs currently iterating over.
đŁTry It: Looping over Arrays
- Declare an array of the names of five of your friends
- Write a
for-in
loop that uses each name and printsHello, [friend's name]
to the console - Declare an array of the names of four things you want to learn
- Write a
for-in
loop that uses each thing you want to learn and printsI want to learn [thing I want to learn]
to the console
Share with your breakout groups: What did you name your arrays? What word did you use to describe the individual elements (what did you type between for and in in your loops)?
Placeholders & Counters
Sometimes, when iterating over an array, our end goal wonât be to do the exact same thing to each element. Sometimes weâll want to combine elements. Sometimes weâll want to filter through them and only use some of them.
Hereâs a real-life example: Tumblr has an array of posts related to each term. When we first search a term, weâll see all the posts. If we select âLinkâ from the filter drop-down, weâll only see the two posts that are links.
How did Tumblr do that? They iterated over the array of all posts, checked each one for a piece of criteria, and put those that did meet the criteria in a placeholder. After it finished iterating, it returned the placeholder and displayed them in the browser.
Letâs solve a slightly less involved challenge, but one that gets at the same idea. Our goal will be to take an array of numbers and return an array of only the numbers from the original array that are greater than 10.
// start with an array of numbers
var numbers = [1, 4, 23, 14, 5, 7, 11, 6, 92]
// start a placeholder array that will eventually store numbers over 10
var largeNumbers = [Int]()
// iterate over the array
for number in numbers {
}
In the code above, we set up our placeholder and our for in
loop. Now, we need to do some work inside the curly braces of the loop.
var numbers = [1, 4, 23, 14, 5, 7, 11, 6, 92]
var largeNumbers = [Int]()
for number in numbers {
// check if the current number being iterated over is greater than 10
if number > 10 {
}
}
In the code above, we wrote a conditional to check the value of the current number against 10. Now, we need to write code inside that conditional.
var numbers = [1, 4, 23, 14, 5, 7, 11, 6, 92]
var largeNumbers = [Int]()
for number in numbers {
if number > 10 {
largeNumbers.append(number)
}
}
At this point, our largeNumbers
array is holding all four numbers greater than 10, but we arenât ever printing it out, so itâs hard to see that.
var numbers = [1, 4, 23, 14, 5, 7, 11, 6, 92]
var largeNumbers = [Int]()
for number in numbers {
if number > 10 {
largeNumbers.append(number)
}
}
print(largeNumbers)
Try It: Placeholders
Declare an array that contains at least five strings and store it in a variable. You choose what the words are!
Use a for in
loop to create a new array of the words from your original array than have less than 6 characters. Use console.log()
to verify your new array holds what you think it does.
Click here for a Spicy Challenge đ¶đ¶đ¶
Declare a function called findLongestWord
. It should iterate over an array of strings. Your function should return one string, the string from the original array that had the greatest number of characters. If there is a tie for the greatest number of characters, return the last one that is in the array.
for-in
Loops without Collections
We can also use for-in
loops without a collection, like an array or dictionary. In this case, we would do this because we want to perform a specific action, a certain number of times. There are a couple of differences in the syntax you might see when we arenât iterating over an array. See the code below:
for _ in 1...4 {
print("Hello!")
}
Why didnât we use a variable here? We didnât need one. We werenât iterating over an array and trying to do something with each element, so we use the underscore.
for number in 1...4 {
print(number)
}
In the example above, we did declare a variable, number
- it will behave as if we were iterating over [1, 2, 3, 4]. (This doesnât mean 1...4
really is an array, though.) If youâre interested in learning more about this, read up on the Range documentation.
Try It: Looping without Collections
Write a for-in
loop that prints Are we there yet?
to the console 100 times.
Write a for-in
loop that prints I've had ___ frappuccinos today ...
to the console 10 times, with the numbers 1 - 10 filled in for the blank.
Click here for a Medium Challenge đ¶đ¶
Write a for-in
loop that prints I've had ___ frappuccinos today ...
to the console 5 times, starting at 7.
Click here for a Spicy Challenge đ¶đ¶đ¶
Write a for-in
loop that prints I've had ___ frappuccinos today ...
to the console 10 times, with the numbers 0 - 9 filled in for the blank. However, the second statement printed out technically has incorrect grammar. That sentence should say I've had 1 frappuccino today ...
, with frappuccino being singular. How can you utilize other concepts you've learned this week to accomplish that?
Loops
Weâre really getting into some complicated code! Work through the practice below to make sure you have this down.
Practice: Loops
Check Your Understanding
Let's take some time to answer the following questions in our journals, and then discuss our answers together.
- What is a for-in loop (in Swift)? What does it do?
- What are the different ways you can use a for-in loop?
- How can for-in loops be useful? What do you think is the point of them?
- Can you brainstorm some ways that one of your favorite apps might make use of a for-in loop?
More Practice
At this point, you have the tools to do just about anything with loops! If youâd like more practice before moving on, check out the Leveled Array Practice Exercises.