0

我有以下结构,其中GroceryData有关于部分的详细信息[GrocerySection],这反过来又具有要在部分中显示的项目[Grocery]

struct GroceryData {
    var showFavorites:Bool = false
    var sections:[GrocerySection] = [GrocerySection(sectionName: "Common Items")]

}

struct GrocerySection {
    var sectionName:String
    var items:[Grocery] = [Grocery(id:1, name: "Milk", isFavorite: true, price: 1.99)]
}



struct Grocery: Identifiable,Hashable, Codable {
    var id:Int
    var name:String
    var isFavorite:Bool
    var price:Float
}

可识别属性的关键路径应该是什么。

struct ContentView: View {

    var data:GroceryData
    var body: some View {
        List(data.sections, id: \GrocerySection.items.id) { (item) -> Text in
            Text("Hello")
        }
    }
}

在此处输入图像描述

4

2 回答 2

1

由于您正在处理部分,因此这可能有效:

    List(data.sections, id: \.self.sectionName) { section in
        Text("hello section \(section.sectionName)")
    }

只要 sectionName 是唯一的,否则你总是可以添加和 id 字段。

如果你想遍历项目,你可以试试这个:

    List(data.sections, id: \.self.sectionName) { section in
        ForEach(section.items) { item in
            Text("\(item.name)")
        }
    }
于 2020-04-27T01:42:06.897 回答
0

您迭代部分列表,因此GrocerySection必须是可识别的,例如

struct GrocerySection: Identifiable {
    var id = UUID()        // << this
//     var id: String { sectionName }   // << or even this
    var sectionName:String
    var items:[Grocery] = [Grocery(id:1, name: "Milk", isFavorite: true, price: 1.99)]
}

然后你可以写

List(data.sections) { (section) -> Text in
    Text("Hello")
}

或者如果每个部分名称都是唯一的,则使用 keypath,如

List(data.sections, id: \.sectionName) { (section) -> Text in
    Text("Hello")
}
于 2020-04-27T04:27:46.123 回答