Programming in Swift: Fundamentals

Oct 19 2021 · Swift 5.5, iOS 15, Xcode 13

Part 3: Control Flow

20. For Loops

Episode complete

Play next episode

About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 19. Challenge: While Loops Next episode: 21. Challenge: For Loops

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 20. For Loops

Update Notes: The student materials have been reviewed and are updated as of October 2021.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

Now 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. Now in this video, you'll continue learning about flow control in Swift using another loop known as the for loop. Now a for loop, it's a little different than a while loop. With a for loop. you aren't checking each time to see if a condition is still true. But instead, the loop will run a certain number of times, determined by the number of elements in a sequence. Now in this exercise, we're only going to worry about using a specific type of a 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. So 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. Well, that's called a closed range and it looks like this. The zero is called lower bound of the range, and the five is the upper bound. The three dots are what define this as a closed range. And that says, we want to include the upper bound in the range. Now, instead of saying closed range, you might say, this is a range from zero to five 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. The third dot is replaced by a < symbol. And that indicates you don't want to include the value of the upper bound. 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 or less than the second number. So 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. So for instance, what if I had some useful value stored in a variable? Then I could declare a closed range like this using the variable or a half open range even. Maybe it's important that we have a range that ends at exactly one number less than that variable. You'll actually find this happens a lot as your programs become more complicated. So, it's really useful to have multiple ways to define ranges. So, 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 loop runs is controlled by the range you give it. Let's say you want to add up all the numbers in a range, such as one through 10, you could do that with a while loop for sure, but a for loop actually shows your intent more clearly. So first, you'll need a variable to store the sum, which you'll initialize to zero. And then create a new count constant to use in this playground and set it to 10. So now you can create the for loop. A for loop starts with a keyword for and then you name a constant, i standing for index is a good choice here, then the keyword in and then you put the range. So this reads like for i in one two count. Now 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. So you want to add up all the numbers in this range. So you simply add the value of the constant, i, to the sum variable, each time to the loop. When the for loop starts, i is set to the first value of your range. In this case, one. Each iteration of the loop automatically sets the value of i to the next value in the range, and then adds that to the sum until your range runs out of values and the loop ends. And if I execute my playground and I print the value of sum, I can see that adding the numbers from one to 10 inclusive ends up as 55. That's cool, I didn't think it would be that high. In this for loop, you used a constant, i, inside the loop. So you can prove that i is a constant by trying to set it to a different value inside the loop. And if I execute, I'll see, cannot assign to value, i is a constant. So I'll take that out. 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 that you didn'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. So try making one more loop that just prints out any word you want, but replace the i with an underscore. And you can see 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 here at any point through the loop. At the end of the last challenge, I mentioned there was another way to specify conditions in Swift. You may have noticed that the for loops you'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 curler braces like this. Simply use the WHERE keyword and the condition you want to check. And you can see that my loop doesn't execute 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 a loop to set conditions. What if you want to have a loop that only prints out odd numbers? Create another for loop with i as the constant and a range of one through count. And inside, use a print statement that says i is an odd number. So right now, it's just printing it out for every number which isn't exactly what you want. But how do 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 five by two, you'll have remainder of one, that's what's leftover. That's actually true of any odd number, not just five. And 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. You'd read that as five mod two. And if I execute my playground again, you can see the remainder is one. So to only print the odd numbers in this loop, just add the WHERE clause to your for loop and check if i mod two is equal to one. And that means that i would be odd. So execute again, and you'll see it's working. You'll only see the odd numbers printed out. Now 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. So it may feel a little like there's usually more than one way to do exact the same thing in Swift, and that's true. In computer programming, there are often a lot of ways to achieve the same result. And when you're just starting out, you can really learn a lot simply by trying out different ways to solve the same problem. But as your programs become more and more complex, a good rule of thumb is to choose the method that's easiest to read and best conveys your intent. So, with time and experience, you'll discover that future you and past you don't always agree on what that means, and that's okay. When you disagree with your past self, it usually means you've learned something and now you're better equipped to write code that makes sense to your future self. So I've got some challenges for you in the next video where you can get to try out several ways to build loops for several scenarios. I'll see you there.