官术网_书友最值得收藏!

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>. <value> is 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>. <sequence> is where we want to provide it with our sequence of numbers. Let's write the following into Playgrounds:

Notice that, in our Debug Panel, we can 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 can 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 the value variable, and in the second one, we used the index variable. You can make these variables whatever you choose them to be.

Also, in the two preceding examples, we used constants, but we could just use the ranges within the loop. As a next step, you need to add the following:

Now, you will see 0 to 3 print inside the Debug Panel.

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

主站蜘蛛池模板: 张北县| 五指山市| 蓬安县| 徐水县| 黄冈市| 卫辉市| 泰兴市| 焉耆| 岑溪市| 灵璧县| 汝阳县| 丰台区| 建德市| 浙江省| 页游| 西畴县| 蒙城县| 新晃| 沈丘县| 信宜市| 肥乡县| 静乐县| 顺义区| 迭部县| 台山市| 松江区| 玛沁县| 闽清县| 南雄市| 涿鹿县| 汝阳县| 梓潼县| 三门峡市| 甘洛县| 安化县| 洛川县| 满洲里市| 丹江口市| 凤山县| 平安县| 怀柔区|