There is a more powerful way to use the for loop in Swift.
For loops can be declared with a variable and a range to iterate over:
for variable in range {
instruction1
instruction2
...
}
Let's break down each component:
The
variabletakes on each successive value in the range, starting from the first value. It is set up automatically before the loop begins.The
rangedefines the sequence of values the loop iterates over. The loop continues as long as there are remaining values in the range.After each iteration the
variableautomatically advances to the next value in the range, prior to the next check.
Example:
for i in 0..<4 {
print("Hello world!")
}
// This code prints "Hello world!" on four different lines
Let's break down this code:
The range starts at
0. The loop variableiis initialized to0so the loop starts counting from 0.The range is
0..<4, meaning the loop will run as long as the iterator variable,i, is less than 4.After each iteration
iautomatically advances to the next value. This means that after running the code inside{},iwill get increased by 1.
This is what the computer does behind the scenes during this loop:
0. Creates and initializes a variable i = 0
1. First iteration:
a. Is i < 4 true? <=> Is 0 < 4 true? Yes.
b. Run the code inside {}. Print "Hello World".
c. i advances => i = 1
2. Second iteration:
a. Is i < 4 true? <=> Is 1 < 4 true? Yes.
b. Run the code inside {}. Print "Hello World".
c. i advances => i = 2
3. Third iteration:
a. Is i < 4 true? <=> Is 2 < 4 true? Yes.
b. Run the code inside {}. Print "Hello World".
c. i advances => i = 3
4. Forth iteration:
a. Is i < 4 true? <=> Is 3 < 4 true? Yes.
b. Run the code inside {}. Print "Hello World".
c. i advances => i = 4
5. Fifth iteration:
a. Is i < 4 true? <=> Is 4 < 4 true? No.
b. Exit the loop.
Assignment
Let's print "I promise to learn coding." 5 times using a for loop.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.