user14023669
user14023669

Reputation:

How to iterate over an array in a LazyVGrid

I am trying to iterate over an array of objects inside a LazyVGrid so as to print out the first name of each contact into each cell. The issue is, I am getting error: "Type '()' cannot conform to 'View'" on LazyVGrid...

After looking up potential fixes, I am seeing that some are saying we can't use functional code in a grid, but apple is using functional code in their documentation on how to use a LazyVGrid, so I am not understanding how this is true.

Does anyone know what I am missing?

Please see below code:

var body: some View {
    NavigationStack {
    VStack {
        ScrollView {
            LazyVGrid(columns: threeColumnGrid) {
                // employeeContactsTempData is simply an array of objects containing contact related data
                employeeContactsTempData.forEach({ contact in
                    VStack {
                        Text(contact.firstName)
                    }
                    
                })
            }
        }
            Spacer()
        }.background(.blue)
    }
}

Upvotes: 0

Views: 609

Answers (1)

mucahid-erdogan
mucahid-erdogan

Reputation: 276

You should use ForEach to iterate over an array to create views.

LazyVGrid(columns: threeColumnGrid) {
    // Use id argument if your contact model is not identifiable.
    ForEach(employeeContactsTempData, id: \.self) { contact in
        VStack {
             Text(contact.firstName)
        }  
    }
}

Upvotes: 0

Related Questions