Chapter: For Loops
For loops are an important language element in Swift. The following text is about it.
In the meantime, we have found that it makes little sense to document all the individual challenges. We think that the Internet is full of possible solutions to each challenge, so we only ever show the last solution from each learning chapter here.
Also, we have now (2022) started documenting progress in more detail, so we can address individual challenges as needed.
Challenge solution code: For-Loops (last challenge)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// MIT License (MIT) Copyright (c) 2021 Rosi Regner
// Challenge: For loops (last challenge)
func collectGems() {
moveAndCollect()
turnLeft()
collectAndTurnAround()
forwardAndLeft()
collectAndTurnAround()
forwardAndLeft()
moveAndCollect()
}
func moveAndCollect() {
moveForward()
collectGem()
}
func forwardAndLeft() {
moveForward()
turnLeft()
}
func collectAndTurnAround() {
moveAndCollect()
turnAround()
}
func turnAround() {
turnLeft()
turnLeft()
}
for i in 1 ... 3 {
collectGems()
moveForward()
}
collectGems()
Our verdict
The for loops were not a big challenge for Rosi. She got the hang of it in no time.