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

The repeat...while loop

The repeat...while loop is pretty similar to a while loop in that it continues to execute the set of statements until a condition becomes false. The main difference is that the repeat...while loop does not evaluate its bool condition until the end of the loop. Here is the basic syntax of a repeat...while loop:

repeat {
// statement
} <condition>

Let's write a repeat...while loop in Playgrounds and see how it works. Add the following to Playgrounds:

var x = 0

repeat {
x += 5
print("x: \(x)")
} while x < 100

print("repeat completed x: \(x)")

You will notice that our repeat...while loop executes first and increments x by 5, and after, as opposed to checking the condition like it did before, as with a while loop, it checks to see whether x is less than 100. This means that our repeat...while loop will continue until the condition hits 100. Here is where it gets interesting.

Let's add another repeat...while loop after the one we just created:

repeat {
x += 5
print("x: \(x)")
} while x < 100

Now, you can see that our repeat...while loop incremented to 105 instead of 100, like the previous repeat...while loop. This happens because the bool expression does not get evaluated until after it is incremented by 5. Knowing this behavior will help you to pick the correct loop for your situation.

主站蜘蛛池模板: 大新县| 杭锦旗| 万安县| 库车县| 泉州市| 高安市| 正蓝旗| 华安县| 方正县| 乌海市| 社旗县| 祁东县| 安庆市| 雷波县| 和硕县| 钦州市| 博罗县| 东城区| 新宾| 西青区| 应城市| 洛隆县| 怀宁县| 邻水| 鲁甸县| 英吉沙县| 正蓝旗| 米林县| 河池市| 阿克苏市| 丽江市| 会泽县| 蕲春县| 任丘市| 杭锦后旗| 安丘市| 青冈县| 叙永县| 噶尔县| 绥滨县| 肥东县|