Introduction to Loops
If we wanted someone to walk 5 steps toward us, it's easier to say just that – rather than say:
- walk 1 step
- walk 1 step
- walk 1 step
- walk 1 step
- walk 1 step
In the same way, we can use a loop to have a computer repeat an instruction – or a block of multiple instructions – more than once.
Creating a loop
To make a function in Swift Playgrounds, just begin typing the keyword for
, and then press the Return key to use autocomplete:
You will then have a template for a function that you can fill in:
First, fill in the number.
That describes how many times you want the block of code to run.
Let's choose 5:
Next, copy the code shown here below into the body of the loop:
turtle.penDown()
turtle.forward(distance: 50)
turtle.penUp()
turtle.forward(distance: 50)
... replacing the placeholder:
... with the code:
The opening {
marks the start of the code block that will be repeated.
The closing }
marks the end of the code block that will be repeated.
If you press Command-Shift-R to step through the code in the playground, you will see how the loop repeats the code: