Learn
for
-in
loops also give us the flexibility to choose how we want to iterate over a sequence with the stride()
function:
stride(from: a, to: b, by: c)
Notice, in order to use the stride()
function we have to supply 3 values separated by commas. When we use it in a for
-in
loop:
for num in stride(from: 0, to: 6, by: 2) { print(num) }
It prints out:
0 2 4
The values we provide functions are called arguments. In each argument there is an argument label, e.g. from:
, to:
, by:
. We’ll cover more about how functions work in a later lesson, but here’s a sneak peek:
- The first argument,
from: 0
is the starting number of the sequence (0
). - The second argument,
to: 6
is the end of the sequence (6
). But notice, we didn’t print out6
which means this end number is not included. - The third argument,
by: 2
determines how much to increment (or decrement if we use a negative number) during each iteration. Here’s how the value ofnum
changes in the loop:
iteration # | num Value |
---|---|
first | 0 |
second | 2 |
third | 4 |
Instructions
1.
Currently in Countdown.swift we have a for
-in
loop that counts forwards: 1, 2, 3
. Change the sequence in the loop to use stride()
to count backwards with the following arguments:
from: 3
to: 0
by: -1
That’s right, we can even go backward!
Take this course for free
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.