Leave a rating/review
Notes: 20. For Loops
Update Notes: The student materials have been reviewed and are updated as of October 2021.
So far, you’ve learned how to control the flow of execution in your apps using the decision-making powers of if statements and the while loop.
In this video, you’ll continue learning about flow control in Swift, using another loop known as the For Loop. A for loop is a little different than a while loop. With a for loop, you aren’t checking each time to see if a condition is true. Instead, the loop will run a certain number of times, determined by the number of elements in a sequence.
In this exercise, we’re only going to worry about using a specific type of sequence called a countable range.
So, before you get into using For Loops, you need to know how to use the Countable Range data type, which lets you represent a sequence of numbers. Let’s try creating a few ranges!
Let’s say you want to represent the sequence of zero all the way up to and including five. That’s called a closed range, and it looks like this:
let closedRange = 0...5
The zero is called the lower bounds of the range and the 5 is the upper bound. The three dots are what defines this as a closed range, and says that we want to include the upper bound in the range.
Instead of saying “closed range” you might say this is “a range from 0 to 5, inclusive”. That means it includes five.
If you don’t want to include the upper bounds, say if you only want to count from zero to four, you can use a half open range, like this:
let halfOpenRange = 0..<5
The third dot is replaced by a less-than symbol, and that indicates that you don’t want to include the value of the upper bounds.
And you can only make a range that counts up! You can’t make a range that counts down. So therefore, the first number must be equal to or less than then second number.
These examples seem trivial with actual numbers, but once you start using variables in there, you’ll quickly see how the closed and half-open ranges make a big difference in how readable your code is. For instance, what if I had some useful value, stored in a variable?
var usefulValue = 5
Then I could declare a closed range like this, using the variable
let closedRange = 0...usefulValue
Or a half-open range, even:
let halfOpenRange = 0..<usefulValue
Maybe it’s important that we have a range that ends at exactly one number less than that constant. You’ll actually find this happens a lot as your programs become more complicated, so it’s useful to have multiple ways to define ranges. Now you’re ready to try out a For loop!
In a while loop, you executed a chunk of code While a certain condition was met. With For loops, the number of times the loop runs is controlled by the range you give it. Let’s say you want to add up all of the numbers in a range, such as 1 through 10.
You could create that with a while loop, for sure, but a for loop actually shows your intent more clearly. First, you need a variable to store the sum, which you’ll initialize to zero.
var sum = 0
And then create a new count constant to use in this playground, and set it to 10.
let count = 10
Now you can create the for loop. It starts with the keyword for, then you name a constant (i, standing for “index” is a good choice), then the keyword in, and then you put the range.
for i in 1...count {
}
So this reads like “for i in 1 to count”. What’s interesting is that you didn’t actually declare i anywhere above. What you’ve done here is to declare a temporary constant, in this case, i, that only hangs around for one iteration of the loop, then i is destroyed and created again for the next iteration.
You want to add up all of the numbers in that range, so you simply add the value of the constant, i, to the sum variable, each time through the loop:
sum += i
When the for loop starts, i, is set to the first value of your range: 1.
Each iteration of the loop sets the value of i to the next value in the range, and adds that to sum, until your range runs out of values and the loop ends. And adding the numbers from one to ten, inclusive, ends up as 55! Cool - I didn’t think it would be that high!
In this for loop, you used a constant, i, inside the loop. You can prove that i is a constant, by trying to set it to a different value inside the loop:
i = 20
You should see an error, like this one:
But what if you don’t care about the value of i in your loop?
When you learned how to use tuples, you saw a way to ignore a value we don’t care about storing. And that’s an underscore! You’ll see underscores used throughout the Swift language to say “I don’t care about naming or storing this thing”. Try making one more loop that just prints out any word you want, but replace the i with an underscore:
for _ in 1...count {
print("roar")
}
You can see that the loop still runs, but Swift doesn’t bother to create that temporary constant. This can be more clear to other people reading your code, that you don’t care about the actual index you’re at at any point through the loop.
At the end of the last challenge, I mentioned that there was another way to specify conditions in Swift.
You may have noticed that the for loops we’ve written so far are always going to run as long as you give them a valid range to run with. But what if you want to set a condition? What if you want to say “I only want to run this loop if count is greater than 100”?
You can use a where clause to do that! Just add it between the range and the curly braces like this:
for _ in 1...count where count > 100 {
print("roar")
}
Use the where keyword and then the condition you want to check. You can see this loop no longer executes at all, because count is only 10.
You can use boolean logic to create more complex sets of conditions, just like with while loops and if statements. With for loops, you can also use the constant of the loop to set conditions. What if you wanted to have a loop that only prints out odd numbers?
Create another for loop with i as the constant and a range of 1 through count:
for i in 1...count {
}
And inside, use a print statement that says “i is an odd number:
for i in 1...count {
print("\(i) is an odd number.")
}
Right now it’s just printing that for every number, which isn’t true!
But how can you know if a number is odd? Well, an odd number always has a remainder when you divide it by two.
So, if you divide 5 by 2, you’ll have a remainder of 1. That’s actually true of any odd number, not just 5.
There’s a neat operator in Swift that calculates the remainder for you: it’s called the modulo operator, or just mod for short. It looks like a percent sign:
5 % 2
You’d read that as 5 mod two, and you can see the remainder is one. To only print the odd numbers, add the where clause to your for loop, and check if i mod two is equal to one, meaning that i is odd:
for i in 1...count where i % 2 == 1 {
Check the console, you’ll see that it’s working. You only see the odd numbers printed out.
At this point, you’ve seen how you can create flow control with if/else statements while loops, for loops, and if you keep working through this course, you’ll learn even more ways.
It may feel like there’s usually more than one way to do exactly the same thing, and that’s true! In computer programming, there are often many ways to achieve the same result.
When you’re just starting out, you can learn a lot simply by trying out different ways to solve the same problem.
As your programs become more complex, a good rule of thumb is to choose the method that’s easiest to read and best conveys your intent.
With time and experience, you’ll discover that future-you and past-you don’t always agree on what that means.
And that’s ok! When you disagree with your past self, it usually means you’ve learned something, and you’re better equipped to write code that makes sense to your future self.
I’ve got some challenges for you in the next video where you can get to try out several ways to build loops for certain scenarios. See you there!