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

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.

主站蜘蛛池模板: 新和县| 瓦房店市| 乐昌市| 巴彦淖尔市| 武鸣县| 佛冈县| 弥勒县| 壶关县| 东台市| 繁峙县| 晋江市| 新民市| 德钦县| 石棉县| 随州市| 临夏市| 古蔺县| 峡江县| 遂川县| 阿克陶县| 科技| 仪陇县| 宾川县| 铁力市| 内丘县| 时尚| 马龙县| 东乌| 梓潼县| 东至县| 澄城县| 洛隆县| 定边县| 石渠县| 南木林县| 江山市| 玉林市| 洪洞县| 双鸭山市| 五家渠市| 安庆市|