While Loops in Swift
- The Coach
- May 16, 2020
- 2 min read
When it comes to loops it can get a bit confusing to decide whether to use a for-in loop or a while loop. To a beginner it may not be very clear when you first study loops as to when each one should be used. Read my other post on for loops and also how for loops could be used to iterate over a array and also how to use nested for loops
A while loop starts by evaluating a single condition. If the condition is true, a set of statements is repeated until the condition becomes false.
Here’s the general form of a while loop, dont confuse this with an IF statement.
while condition {
statements
}
So if you were to do this in some kind of pseudocode it would be along the lines of a conditions is checked, if its true the code in the statement is executed and then repeated again till the specified condition become false.
A great simple example of this is like if you needed to do a countdown timer in your app.
var number = 5
while number > 0 {
print(number)
number -= 1
}
print("Start the race")
Output
5
4
3
2
1
Start the race!
Here you can see that the count begins and keeps progressing downwards from 5 all the way to 1 and the program does this by knowing it should continue with the countdown [condition is checked → is the count greater that zero, then print the count and keep repeating until it hits zero. At zero the condition is in fact false so this is when the loop ends and then 'Start the race' is printed.
Practical examples where a While Loop would be useful in coding :
1. When you need to have a timer in an app
2. There is a need to keep a running score going in an app
3. A learning app where you are going through say multiple choice questions
Comments