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

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.

主站蜘蛛池模板: 汪清县| 新余市| 博爱县| 綦江县| 清苑县| 安乡县| 噶尔县| 科尔| 乌海市| 崇信县| 如皋市| 都江堰市| 广平县| 东阳市| 南雄市| 咸宁市| 阆中市| 安化县| 宜章县| 鄂州市| 含山县| 涿鹿县| 南安市| 菏泽市| 永嘉县| 宜丰县| 房山区| 岳阳市| 海安县| 江川县| 常德市| 和林格尔县| 赞皇县| 雅江县| 安庆市| 武功县| 平果县| 景宁| 永吉县| 营山县| 柞水县|