The ForEach
view is a powerful tool in SwiftUI that allows us to easily iterate over an array or a range and generate views based on the iteration. It simplifies the process of creating repetitive views, such as lists or grids, by reducing the code required.
Let’s start with a basic example. We can use ForEach
to generate three Text
views that display the numbers from 0 to 2:
ForEach(0..<3) { number in
Text("\(number)")
}
In this example, we use the ..<
operator to create a range from 0 to 2. The number
variable represents each element of the range as we iterate through it.
To prevent the views from overlapping, we can embed them in a VStack
and add some padding:
VStack {
ForEach(0..<3) { number in
Text("\(number)")
}
.padding()
}
The padding()
modifier helps to add spacing between the views.
A common use case for ForEach
is inside a List
view. Here’s how we can use it:
List {
ForEach(0..<3) { number in
Text("\(number)")
}
}
This will create a list with the generated views.
In fact, using ForEach
inside a List
view is so common that we can actually omit ForEach
and iterate directly from the List
:
List(0..<3) { number in
Text("\(number)")
}
Both approaches yield the same result.
In addition to ranges, we can also iterate over an array using ForEach
. Let’s say we have an array of fruits:
let fruits = ["Apple", "Pear", "Orange"]
// ...
List {
ForEach(fruits, id: \.self) { fruit in
Text(fruit)
}
}
In this case, we specify the id
parameter as \.self
to uniquely identify each item in the array. For built-in types like strings, using \.self
works out of the box. However, if you’re iterating over a custom struct, you’ll need to ensure that it conforms to the Identifiable
protocol or provide a unique identifier.
With the ForEach
view in SwiftUI, iterating over arrays or ranges and generating views becomes simpler and more efficient. It’s a versatile tool that can be used in various scenarios, from basic lists to more complex UI components.