为什么这个 ForEach 循环不断导致错误?

问题描述

我遇到了这个 ForEach 循环的问题。我试图让它循环遍历一个数组,但它不断给出一个未知的错误,上面写着“无法为表达式生成诊断;请提交错误报告并包含项目'。当我删除 ForEach 循环时,错误消失了。

这是出错的文件

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)
        }

    }
}

}

这是 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
    }

}

对导致此错误的原因有任何想法吗?

解决方法

您需要另一个可识别的

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
    
}