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

Loops

Let's learn how to implement repetitive tasks. There are several ways to do that, using different loops: while, for...in, and repeat...while. The most popular one is the for...in loop. Here is what the basic form looks like:

let collection = [1, 2, 3]
for variable in collection {
//do some action
}

The code will be interpreted like this: the variable will be set to all possible values, which are stored in the collection. If the collection is empty, then no code will be executed. If there are some elements, then the body of the loop (the code in curly braces) will be executed for each element of the collection. The variable loops through every single element and can be used in code.

We need an example to illustrate this. Let's use the following code to print all numbers from 1 to 10, inclusive:

var sum = 0
for index in 1...10 {
sum += index
print("(index)")
}
print("Sum: \(sum)")
//sum is equal to 55

The sum of all numbers from 1 to 10 is stored in a separate variable and the code prints every single number on a new line. The sequence defined with 1...10 is converted to a collection (we can think of it as an array), which is fueling the for...in loop.

We can use variables or constants to define custom ranges of numbers.

Take a look at the following code:

let threeTimes = 3
for _ in 1...threeTimes {
print("Print this message.")
}

Using _ (underscore) we declare that the argument should ignore the values set in the variable, and it doesn't matter to the rest of the code. The code will print three times: Print this message.

主站蜘蛛池模板: 梅河口市| 台州市| 隆尧县| 通辽市| 湾仔区| 仁化县| 斗六市| 辰溪县| 布尔津县| 祁阳县| 新平| 淮南市| 云龙县| 泰来县| 丹江口市| 高尔夫| 勐海县| 孙吴县| 青州市| 舟山市| 太谷县| 苏州市| 丽水市| 扎鲁特旗| 枞阳县| 门源| 灯塔市| 牙克石市| 辛集市| 兰坪| 新竹县| 新建县| 航空| 庆阳市| 宜兰县| 蓬莱市| 莆田市| 台东县| 宜昌市| 柏乡县| 长葛市|