Search code examples
swiftswiftuiswiftui-foreach

Why does this ForEach loop keep causing an error?


I'm having an issue with this ForEach loop. I'm trying to get it to loop through an array but it keeps giving an unknown error which says 'Failed to produce diagnostic for expression; please submit a bug report and include the project'. When I delete the ForEach loop, the error goes away.

This is the file that's giving the error

struct ReceiptView: View {

let item: ItemsStruct

var body: some View {
    VStack {
        
        // Header
        HStack {
            VStack(alignment: .leading) {
                Text(item.company)
                    .font(.title2)
                    .fontWeight(.semibold)
                Text(item.date)
                    .font(.caption)
            }
            Spacer()
            Menu {
                Text("Menu Item 1")
                Text("Menu Item 2")
                Text("Menu Item 3")
            } label: {
                Image(systemName: "ellipsis.circle")
                    .scaleEffect(1.2)
            }
        }.padding()
        
        
        // FIXME: This ForEach is causing an error
        ForEach(item.products) { prod in
            Text(prod.product)
        }

    }
}

}

And This is the ItemsStruct:

public struct ItemsStruct: Identifiable {
    public let id = UUID()
    let company: String
    let date: String
    let total: String
    let products: [itemsArray]

    struct itemsArray {
        let product: String
        let quantity: Int
        let totalPrice: Double
    }

}

Any thoughts on what's causing this error?


Solution

  • You need another Identifiable

    public struct ItemsStruct: Identifiable {
        
        public let id: UUID = UUID()
        let company: String
        let date: String
        let total: String
        let products: [ItemsArray]
        
    }
    
    struct ItemsArray: Identifiable {
        
        let id: UUID = UUID()          // <<: Here!
        let product: String
        let quantity: Int
        let totalPrice: Double
        
    }