ForEach is a powerful SwiftUI view that allows you to iterate over a collection of data and generate views for each element. It’s typically used inside other SwiftUI views like List, VStack, or HStack to create dynamic, repeating elements based on data. Here’s a breakdown of how ForEach works and some example use cases.
Basic Syntax
The basic syntax for ForEach looks like this:
ForEach(data, id: \.self) { item in
Text(item)
}
Parameters
- Data: The collection you want to iterate over.
- ID: A unique identifier for each item in the collection. This helps SwiftUI track which views correspond to which data items, allowing efficient updates.
- Content: A closure where you define the views for each element.
Examples
1. Using ForEach with an Array of Strings
let names = ["Alice", "Bob", "Charlie"]
var body: some View {
VStack {
ForEach(names, id: \.self) { name in
Text("Hello, \(name)!")
}
}
}
2. Using ForEach with a Range
When you just need a fixed number of views, you can use a Range:
var body: some View {
VStack {
ForEach(0..<5) { index in
Text("Row \(index)")
}
}
}
3. Using ForEach with Identifiable Data
If your data model conforms to Identifiable, you can omit the id parameter:
struct Item: Identifiable {
let id = UUID()
let name: String
}
let items = [Item(name: "Apple"), Item(name: "Banana"), Item(name: "Cherry")]
var body: some View {
VStack {
ForEach(items) { item in
Text(item.name)
}
}
}
4. Nested ForEach for Grids
You can nest ForEach to create grids or complex layouts:
import SwiftUI
struct ContentView: View {
let gridItems = Array(1...3)
var body: some View {
VStack {
ForEach(gridItems, id: \.self) { row in
HStack {
ForEach(gridItems, id: \.self) { col in
Text("Row \(row) Col \(col)")
}
}
}
}
}
}
Important Notes
- Uniqueness: Ensure each item in your collection has a unique identifier to avoid unexpected behavior.
- Identifiable: Making your data
Identifiablesimplifies the code, especially when dealing with complex data models.