NNikN
NNikN

Reputation: 3852

Specify Key Path in a List Swift UI

I have below structure , where GroceryData has details about the section as [GrocerySection] , this in turn has items to be displayed in the section as [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
}

What should be the key path for the identifiable property.

struct ContentView: View {

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

enter image description here

Upvotes: 0

Views: 1220

Answers (2)

Asperi
Asperi

Reputation: 258345

You iterate list of sections so GrocerySection must be identifiable, like

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

then you can write

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

or using keypath if every section name is unique, as

List(data.sections, id: \.sectionName) { (section) -> Text in
    Text("Hello")
}

Upvotes: 0

since you are dealing with sections, this may work:

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

as long as the sectionName is unique, otherwise you can always add and id field.

If you want to loop over items you can try this:

    List(data.sections, id: \.self.sectionName) { section in
        ForEach(section.items) { item in
            Text("\(item.name)")
        }
    }

Upvotes: 2

Related Questions