Swift for-in Loop
The Swift for-in loop is used to iterate over all elements in a collection, such as a range of numbers, elements in an array, or characters in a string.
Syntax
The syntax for the Swift for-in loop is as follows:
for index in var {
loop body
}
Flowchart:
Example 1
import Cocoa
for index in 1...5 {
print("\(index) times 5 is: \(index * 5)")
}
The element used for iteration in this example is a range of numbers from 1 to 5, represented by the closed range operator (...).
The output of the above program is:
1 times 5 is: 5
2 times 5 is: 10
3 times 5 is: 15
4 times 5 is: 20
5 times 5 is: 25
Example 2
import Cocoa
var someInts:[Int] = [10, 20, 30]
for index in someInts {
print("The value of index is \(index)")
}
The output of the above program is:
The value of index is 10
The value of index is 20
The value of index is 30