← Back to archive

Development · SwiftUI

Data-driven views with ForEach

Generate repeated views from ranges and identifiable collection elements.

Read the Korean original on Velog ↗English translation

Development archive cover

Instead of writing the same view repeatedly, define the relationship between data and presentation once. ForEach can work with a simple range or with identifiable elements in a collection.

Repeating a view

Provide a range and a view builder to create content for each value.

VStack {
	ForEach(0..<10) { index in // Set the iteration range
		Text("Hi, my index is \(index)") // Repeated view
	}
}

Using an array

An array supplies both the values and the number of rows. Its .indices property provides valid indices. id: \.self uses each supplied value as its identity, so those values must be unique and stable for the intended updates.

struct ForEachStudy: View {
    
    let data: [String] = ["Hi", "Hello", "Hey"]
    
    var body: some View {
        VStack {
            ForEach(data.indices, id: \.self) { index in // Iterate over the array
                Text("\(index) is \(data[index])") // Use the array value for each index
            }
        }
    }
}
← Back to archive