SwiftUI Nested ForEach causes Fatal error: each layout item may only occur once
Asked Answered
I

2

11

I'm trying to create a LazyVGrid view to display the contents of objects in an array using nested ForEach statements. The code is causing an app crash with the message "Fatal error: each layout item may only occur once".

Each object contains an array of values that need to be displayed as a row in the grid. The row consists of cell with the object's sku string followed by a number of cells with the integers from the object's array.

I chose to use a class instead of a struct because I need to update the array within the class.

This is the class for the objects in the array.

class RoomPickupData: Identifiable {
    let id = UUID()
    var sku: String = ""
    // Array of counts for sku on a particular date
    var roomsForDate: [Date: Int] = [:]
}

In the code the first ForEach is used to put header information in the first line of the grid.

The next ForEach and the ForEach nested in it are causing the error.

The outer ForEach iterates through the array of objects so I can create a row in the grid for each object. Each row consists of a string followed values from the roomsForDate array. The size of the roomsForDate array is not fixed.

If I comment out the nested ForEach the code executes but with it I get the fatal error.

If I comment out Text(roomData.value.description) so there is noting in the inner ForEach, the code runs fine too. If I replace Text(roomData.value.description) with Text("") the app crashes.

ForEach nesting seems like the best way to accomplish producing a grid view from a two dimensional array or array of objects each containing an array.

I've found other posts showing that nested ForEach statements can be used in SwiftUI.

Here is the code. Your help with this issue is appreciated.

struct RoomTableView: View {
    @ObservedObject var checkfrontVM: CheckFrontVM
    let dateFormatter = DateFormatter()
    
    init(checkfrontVM: CheckFrontVM) {
        self.checkfrontVM = checkfrontVM
        dateFormatter.dateFormat = "MM/dd/yyyy"
    }
    
    func initColumns() -> [GridItem] {
        var columns: [GridItem]
        var columnCount = 0
        
        if self.checkfrontVM.roomPickupDataArray.first != nil {
            columnCount = self.checkfrontVM.roomPickupDataArray.first!.roomsForDate.count
        } else {
            return []
        }
        columns = [GridItem(.flexible(minimum: 100))] + Array(repeating: .init(.flexible(minimum: 100)), count: columnCount)
        return columns
    }
    
    var body: some View {
        if self.checkfrontVM.roomPickupDataArray.first != nil {
            ScrollView([.horizontal, .vertical]) {
                
                LazyVGrid(columns: initColumns()) {
                    Text("Blank")
                    ForEach(self.checkfrontVM.roomPickupDataArray.first!.roomsForDate.sorted(by: {
                        $0 < $1
                    }), id: \.key) { roomData in
                        Text(dateFormatter.string(from: roomData.key))
                    }
                    
                    ForEach(self.checkfrontVM.roomPickupDataArray) { roomPickupData in
                        Group {
                            Text(roomPickupData.sku)
                                .frame(width: 80, alignment: .leading)
                                .background(roomTypeColor[roomPickupData.sku])
                                .border(/*@START_MENU_TOKEN@*/Color.black/*@END_MENU_TOKEN@*/)
                            ForEach(roomPickupData.roomsForDate.sorted(by: { $0.key < $1.key}), id: \.key) { roomData in
                                Text(roomData.value.description)
                            }
                        }
                    }
                }
                .frame(height: 600, alignment: .topLeading)
            }
            .padding(.all, 10)
        }
    }
}

Integral answered 27/8, 2020 at 21:2 Comment(1)
This code not testable, would you prepare minimal reproducible example?Wilful
I
16

Every item in ForEach needs a unique ID. The code can be modified by adding the following line to the Text view in the inner ForEach to assign a unique ID:

.id("body\(roomPickupData.id)-\(roomData.key)")

ForEach(self.checkfrontVM.roomPickupDataArray) { roomPickupData in
    Group {
        Text(roomPickupData.sku)
        .frame(width: 80, alignment: .leading)
           .background(roomTypeColor[roomPickupData.sku])
           .border(Color.black)
        ForEach(roomPickupData.roomsForDate.sorted(by: { $0.key < $1.key}), id: \.key) { roomData in
          Text(roomData.value.description)
            .id("body\(roomPickupData.id)-\(roomData.key)") //<-
          }
        }
       }
Integral answered 29/8, 2020 at 15:28 Comment(0)
E
2

I was facing the same error for ForEach inside ForEach inside a LazyVStack I have solved it by adding the UUID() identifier to the innermost View like

.id(UUID)

Here is an example:

LazyVStack {
    ForEach(vmHome.allCategories, id: \.self) { category in
        VStack {
            HStack {
                Text(category)
                    .font(.title3)
                    .bold()
                    .padding(10)
                Spacer()
            }
            ScrollView(.horizontal) {
                LazyHStack{
                    ForEach(vmHome.getMovies(forCat: category), id: \.self.id) { movie in
                         StandardHomeMovieView(movie: movie)
                             .id(UUID())
                     }
                }
            }
        }
    }
}
Extrapolate answered 18/8, 2021 at 19:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.