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

The while loops

The while loops execute the body of the loop (list of the statements in the body part) until the condition is evaluated to false.

There are two types of while loops. There is the classical while loop, which checks the condition, and, if it holds, then the code in the body is executed. Then the check is performed again and everything is repeated until the condition is evaluated to false. The other variant is the repeat...while loop, which first executes the body, and then does the check. The second type is executed at least once, compared to the first one, which could be completely skipped:

var i = 1
let max = 10
var sum = 0
while i <= max {
sum += i
i += 1
}
print("Sum: \(sum)")

The code sums all numbers from 1 to 10. The condition will be broken once i reaches 11.

We can use repeat...while to do the same:

var i = 1
let max = 10
var sum = 0
repeat {
sum += i
i += 1
} while i <= max
print("Sum: \(sum)")

We can use while to implement the repeat...while loops and the reverse, but with slight modifications. The best rule for picking the right type of loop is to know whether the sequence should be executed at least once. Executing once means that it's much easier to implement it using repeat...while; otherwise, the classical while loop is the best choice.

There are some special conditions which we should handle, but to do so, let's see what they are.

We can use the special words—continue and break—to trigger special behavior while we are in a loop. The continue statement is used when you want to stop the current iteration of the loop and start over. When using this, be careful that you change the value in the condition; otherwise, the loop could be an infinite one, which means that your program won't end.

The break statement is used once we want to stop the entire loop. Be careful when you have nested loops. The break statement stops the current iteration immediately, and then jumps to the very first line after the end of the innermost loop, which contains the break statement. If you want to break two or more nested loops, then you have to find an appropriate way to do so. To be explicit when breaking nested loops, you may use labeled statements. It is a convenient way to give a name of a loop and then to change the flow when using break. It's good to know that break may be used as part of a switch statement. This will be discussed in the next part.

There are a few other special words, such as return , throw, and fallthrough which change the default order of execution of the code. We will get familiar with these later.

主站蜘蛛池模板: 昌邑市| 龙南县| 洪雅县| 湄潭县| 新野县| 桃园市| 永新县| 自贡市| 麻江县| 阳原县| 东山县| 安阳市| 宜兰市| 军事| 巴楚县| 大宁县| 镇江市| 抚宁县| 凌海市| 鹿泉市| 西青区| 阿克苏市| 油尖旺区| 荃湾区| 永胜县| 安乡县| 黄浦区| 井陉县| 全州县| 陈巴尔虎旗| 闽侯县| 屯留县| 连江县| 鹤庆县| 龙里县| 巴塘县| 英德市| 资讯 | 泉州市| 滨海县| 秦安县|