1

I want to make a list with multiple section headers and items based on a date field of a list of items. What is the best way to do this programmatically?

var registrants:[Registration] = [Registration(name:"Joe", date:12/15/2020),Registration(name:"Billy", date:11/12/2020),Registration(name:"Cameron", date:11/10/2020)]

Usually I hardcode and use only foreach loop for items in one specific section like the following:

List {
    Section(header: Text("December 2020")) {
       ForEach(...)
    }
    Section(header: Text("November 2020")) {
       ForEach(...)
    }
    Section(header: Text("October 2020")) {
       ForEach(...)
    }
}

Am looking for a smarter way to do this...

pawello2222
  • 46,897
  • 22
  • 145
  • 209
Rolando
  • 58,640
  • 98
  • 266
  • 407
  • 1
    wrap those sections in a ForEach too – Tad Jan 07 '21 at 04:35
  • Does this answer your question https://stackoverflow.com/a/63193327/12299030? – Asperi Jan 07 '21 at 04:50
  • 1
    Does this answer your question? [How to dynamically create sections in a SwiftUI List/ForEach and avoid "Unable to infer complex closure return type"](https://stackoverflow.com/questions/58574847/how-to-dynamically-create-sections-in-a-swiftui-list-foreach-and-avoid-unable-t) – Andrew Jan 07 '21 at 06:26

1 Answers1

0

To use in a ForEach your data should be Identifiable or there should be some way you can specify id.

struct ContentView: View {
    
    var registrants:[Registration] = [Registration(name:"Joe", date:"12/15/2020"),Registration(name:"Billy", date:"11/12/2020"),Registration(name:"Cameron", date:"11/10/2020")]
    
    var body: some View {
        List {
            ForEach(registrants) { (registration) in //<=Here
                Section(header: Text(registration.date)) {
                    ForEach(0 ..< 5) { item in
                        Text("item \(item)")
                    }
                }
            }
        }
    }
}

struct Registration : Identifiable{ //<= here
    var id = UUID()
    var name: String
    var date: String
}
YodagamaHeshan
  • 4,996
  • 2
  • 26
  • 36