Programming in Swift: Fundamentals

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

Part 3: Control Flow

18. While Loops

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 17. Introduction Next episode: 19. Challenge: While 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: 18. While Loops

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

Transcript: 18. While Loops

What if you had to write some Swift code to print out a string 100 times? It would be tedious to write 100 print statements, but it would also violate the “Don’t Repeat Yourself” rule 99 times.

Luckily, Swift has a tool to help with this: loops. In this exercise, you’ll be trying out one particular kind of loop: the while loop. Their syntax looks like this and they look a lot like an if statement!

The important difference is that as long as the condition of the while loops remains true, the code inside executes. So the condition is checked, if it’s true, the code executes, then the condition is checked again, and so on. You can see why it’s called a loop! The loop ends when the condition is checked and it turns out to be false.

You’ll start by writing a while loop. Then, you’ll create a variant of the while loop called the repeat while loop, and you’ll learn the differences between them.

Download the materials for this section of the course, unzip them, and open the playground for this section. You’ll find a page inside the playground for each video of this part, just like the playground you have for Parts 1 and 2. Navigate to 02 - While Loops, and get started!

To start, let’s create a while loop that will print out the numbers 1 through 9. You’ll need two things: the while loop itself, and a variable to track the number of times we’ve looped.

Start with the variable. Call it i and set the value to 1:

var i = 1

It’s not the most descriptive variable name, for sure. But you’ll notice as you move along in your development career that developers sometimes tend to use single-letter variables, such as i, j, and k for simple loops. In a loop, i is a pretty well-known convention that means “index”. For a simple loop that counts up to nine, i is enough.

Now you’re ready for the loop. Loop syntax starts with while, then a condition. A condition is simply a Boolean expression; you should recall Boolean expressions from the previous part of this course.

In this case, you want to print out the numbers from one to nine. So you want this loop to run up to nine, but no further. The simplest way is to say “while i is less than ten”:

while i < 10

You could also say “i is less than or equal to 9”, which means the same thing.

Finally, you need to tell Swift to print out the value of i each time it goes around the loop. To do that, you add a set of curly braces to hold the code to execute:

while i < 10 {

}

And then inside those curly braces, you tell Swift to print(i):

while i < 10 {
  print(i)
}

Once you’ve printed the value of i, you need to increment i by one before the loop goes around again. Do you remember how to increment numbers? That’s right, with the plus equals operator:

while i < 10 {
  print(i)
  i += 1
}
  • Now when the playground executes, you’ll see the numbers 1-9 appear in the console! Each time around the loop, Swift prints the current value of i, then increments i by one. When i is ten, the condition here is no longer true, so Swift stops executing the loop.

Now, what would happen if you declared i to be ten before the loop started? That’s right, it wouldn’t run. But what if you wanted to guarantee that a loop would execute at least once, before you check the condition for the loop?

You can use a variant of the while loop called the repeat while loop! You may also hear this called a “do while” loop in some other programming languages, but in Swift, it’s the repeat while.

First, put a print statement in there so you can tell in your console where you start counting down:

print("Counting up again")

And you also want to reset your counter to one, so do that after the “Counting up again” line:

i = 1

Remember, you’ve declared this as a variable above, so you don’t need to redeclare i down here; you just need to assign it the value you want.

The syntax for a repeat while loop is sort of backwards to the regular while loop: it starts with “repeat” followed by a set of curly braces with the loop code inside:

repeat {

}

So put the code you want to execute inside the curly braces; print i, then increment i by one:

repeat {
  print(i)
  i += 1
} 

Now, what condition are you going to end with? You want to count up to nine, but remember that this loop will execute first, and then the condition will be checked.

You want this to print the numbers up to and including nine, and then stop. So your condition will be i < 10, again. That means that when i is incremented to nine, the loop will run again, print nine, increment i to ten, and then the condition will be checked again, and the loop will stop.

  • You can see in the console, that your playground counts up to nine, and then counts up to nine again. Nice!~

To see the difference between these two loops, see what would happen if you set i to 10 before the loops started. Change both spots where you assign one to i, and assign it 10 instead

var i = 10

i = 10

Now you can see the difference between the two loops.

  • With the while loop, the condition is checked, but i is not less than ten, so the code inside never executes.

  • The repeat while loop, however, executes the first time and prints out “10”, and then checks the condition, finds the condition is false, and doesn’t repeat.

So the important difference is knowing when the condition is checked. A while loop checks the condition before the loop code, and repeat while checks the condition after.

There you go! Two different flavors of while loops in Swift! And to make sure you really know the difference, I’ve got some challenges for you next, that hopefully won’t throw you for a loop!