With the help of examples, we will learn how to use the for loops in Swift in this article.
Loops are used in computer programming to repeat a section of code.
In Swift, there are three types of loops:
- while Loop
- repeat while Loop
- For Loop
In swift we need to have the multiple iteration in the code of development due to which we required different types of Loops in swift.
While loop in swift
basically while loop in swift is also called as pre tested iteration as condition is checked first then statement is executed.
Syntax for while loop in swift
var i = 5
while ( i >= 0 ) {
print("\(i)")
i--
}
Output : 5 4 3 2 1
Example for while loops in swift
while condition {
statements
}
Here the iteration takes place until the condition is false . while loop is know as pretested as shown above example
2. Repeat while loop in swift
It is known as post tested loop because the condition is tested after the statement execution in the loop. here the statement is executed at least once .
Syntax for repeat while loop
repeat {
statements
} while condition
Example for repeat while loops in swift
var i = 5
repeat {
print("\(i)")
i--
}while ( i > 0 )
Output : 5 4 3 2 1
3. For loops in swift
for loop in swift is basically called as nested loop in swift. for loop is mostly popular iterative loop used in the swift code. it is used basically for arrays, sequence of number or range of number .
Syntax for Loop
for index in sequence{
// statements
}
For loop for arrays in swift
let fruits = ["mango","apple","banana","Kiwi"]
for fruit in fruits {
print ("\(fruit)")
}
OUTPUT: mango apple banana Kiwi
For loop to find the range of index in swift
for index in 1...10 {
print(index)
}
OUTPUT : 1 2 3 4 5 6 7 8 9 10
For Loop in swift for dictionary
let numberOfWheels = ["cycle": 2, "car": 4, "truck": 6]
for (automobile, wheelscount) in numberOfWheels {
print("\(automobile)s have \(wheelscount) Wheels")
}
// cycle have 2 Wheels
// car have 4 Wheels
// truck have 6 Wheels
For loop swift using stride
let interval = 1
let days = 24
for hour in stride(from: 0, to: days, by: interval) {
// render the hour every (0, 1, 2, 3 ... 22, 23)
}
For Closed interval for loop we can use
let days = 24
for hour in stride(from: 0, through: days, by: interval) {
// render the hour every (0, 1, 2, 3 ... 22, 23,24)
}