Iteration
What is iteration?
The following code:
// Create a turtle to draw things for you
var turtle = Tortoise()
// Draw a square
turtle.forward(distance: 50)
turtle.left(angleInDegrees: 90)
turtle.forward(distance: 50)
turtle.left(angleInDegrees: 90)
turtle.forward(distance: 50)
turtle.left(angleInDegrees: 90)
turtle.forward(distance: 50)
turtle.left(angleInDegrees: 90)
// Add the shape drawn by the turtle to the sketch
addShape(drawnBy: turtle)
... draws a square:
However, you may note that the code is somewhat repetitive.
The same pair of instructions (move forward, turn left) repeats four times.
We can write that same code more efficiently, like so:
// Create a turtle to draw things for you
var turtle = Tortoise()
// Draw a square, using a loop
// The block of code marked by the { and } brackets will be iterated over four times
for i in 1 ... 4 {
print(i) // This is here just to illustrate the iteration of this loop
turtle.forward(distance: 50)
turtle.left(angleInDegrees: 90)
}
// Add the shape drawn by the turtle to the sketch
addShape(drawnBy: turtle)
That results in the following:
To write a loop, start typing for
then use the autocomplete feature of Playgrounds to your advantage:
A loop, with placeholders, appears:
Replace the number
placeholder with how many times you want the block of code to repeat.
Replace the code
placeholder with the code that should be repeated.
Hint
You can use the tab
key to move between placeholders quickly.