Using ForEach in SwiftUI to iterate through Views

You will commonly need to iterate through similar views and display them in SwiftUI. For e.g. similar to the image shown below.

Normally we would use ForEach to iterate and display them. ForEach is a structure that computes views on demand from an underlying collection of identified data. In order to make it work, you must provide a unique id. Either the collection’s elements must conform to Identifiable or you need to provide an id parameter to the ForEach initializer. Below is the snippet of code, I use to iterate through them. I use an unique id here.

import SwiftUI

struct Letter : View {
	var id = UUID()
	var body: some View {
		Text("standby text")
		Text("Unique identifier\(UUID())")
		Text("standy text")
	}
}

struct CameraUIView: View {
	var letters : [Letter] = [Letter(), Letter(), Letter(), Letter()]
    var body: some View {
		VStack(alignment: .leading) {
			Text("This text is in the main view. Appears once.")
			ForEach(letters, id: \.id) { letter in
				letter
				Spacer()
						}
		}
    }
}

struct CameraUIView_Previews: PreviewProvider {
    static var previews: some View {
        CameraUIView()
    }
}

This coding style can be helpful when you have a View with multiple subcomponents you wouldn’t want to copy paste.

Leave a Reply

Your email address will not be published. Required fields are marked *