The for...in loop

One of the most common control statements is a for...in loop. It allows you to iterate over each element in a sequence. Let's see what a for...in loop looks like:

for <value> in <sequence> { 
 // Code here 
} 

We start the for...in loop with for, which is proceeded by <value>. This is actually a local constant (only the for...in loop can access it) and can be any name you like. Typically, you will want to give this value an expressive name. Next, we have in, which is followed by <sequence>. This is where we want to give it our sequence of numbers. Let's write the following into Playgrounds:

Notice that, in our Debug panel, we see all of the numbers we wanted in our range.

Let's do the same for our halfClosedRange variable, by adding the following:

In our Debug panel, we see that we get the numbers 10 through 19. One thing to note is that these two for...in loops have different variables. In the first loop, we used value, and in the second one, we used index. You can make these whatever you choose them to be.

In addition, in the two preceding examples, we used constants, but we could actually just use the Ranges within the loop. Add the following:

Now, you see 0 to 3 print inside of the Debug panel.

What if you wanted the numbers to go in reverse order? Let's input the following for...in loop:

We now have the numbers in descending order in our Debug panel. When we add Ranges into a for...in loop, we have to wrap our range inside parentheses so that Swift recognizes that our period before reversed() is not a decimal. Now that we are familiar with loops, there is one more range we need to look at.