Swift provides control flow structure loops
It provides two kinds of while loops in a swift programming language
- while loop
- repeat while loop also called do while loop
Swift while loop
while loop allows you to execute code statements until conditions are not satisfied.
Here is a syntax
while (condition){
// code block
}
condition is evaluated and if true, the code block is executed and stops its code statement execution when the condition is false.
This executes code statements when the condition is met.
Here is a while loop example
var i = 0
while i < 10 {
i+=1
print(i)
}
Output:
1
2
3
4
5
How to loop array with while loop in swift
This is an example of an iteration of an array using a while loop
var words:[String] = ["one", "two", "three","four","five"]
var i = 0
while i < words.count {
print(words[i])
i+=1
}
Repeat while loop in swift
It provides another variation to the while loop, called the repeat while loop. It is also called do while loop in another programming language.
repeat {
code statements
} while [condition]
This executes code statements at least once even condition is false.
Below is an example of array iteration with repeat while loop
var words:[String] = ["one", "two", "three","four","five"]
var i = 0
repeat {
print(words[i])
i+=1
}
while i < words.count