We've explored ForEach
loop in previous articles, but this type of loop can only be used for load SwiftUI views, like rows in a list.
However, we may need to use loops in other situations. In this case we need to use a different variation, but the idea is the same:
let names: [String] = ["Pablo", "Andrea", "Clara", "Mateo"]
for name in names {
print("My name is: \(name)")
}
// My name is: Pablo
// My name is: Andrea
// My name is: Clara
// My name is: Mateo
name
is declared as local variable that will contain each value of the array.
You can go through a number range (or an array indexes) in the same way.
for i in 0..<10 {
print("Number: \(i)")
}
// Number: 0
// Number: 1
// Number: 2
// Number: 3
// Number: 4
// Number: 5
// Number: 6
// Number: 7
// Number: 8
// Number: 9
Be the first to comment