Section in List generated from dates in JSON

Good afternoon (o;

Finally I installed XCode to give Swift and SwiftUI a try two days ago and already have a simple iOS app running which fetches revenues statistics and online shop orders from our online shop with JSON.

Well still some fiddling to do with the layout and looks....

Currently the list view shows all orders sorted by descending order date without any grouping/sections with:

struct OrderView: View {

	@ObservedObject var fetch = FetchOrders()

    var body: some View {
		NavigationView {
			List (fetch.orders) { order in
				NavigationLink {
					OrderDetailView(order: order)
				} label: {
					OrderRow(order: order)
				}
			}
			.refreshable {
				fetch.reload()
			}
			.onAppear {
				self.fetch.reload()
			}
			.navigationTitle("Orders")
		}
		.navigationViewStyle(DoubleColumnNavigationViewStyle())
		.padding()
    }
}

The JSON returned from our server also contains the order date which is currently not used/displayed.

So my question....can the List view be made up with section per order date?

Seen an old post explaining this, but not sure if that is a rather old method which should be avoided:

https://developer.apple.com/forums/thread/128145

I guess in the snippet above there are already other mistakes...but I am just learning since two days and it is quite fun and I was surprised what could be done in this short time compared to Xojo (o;

thanks in advance richard

Replies

I assume that the fetch data are already ordered.

Starting from what was proposed in the older post, I would :

  • prepare an array from fetch:
struct ordersOfADay {
  var day: String // Or Date, if you prefer
  var orders: [Order] // same as in fetch.orders
}
var sortedOrdersPerDay : [ordersOfADay]
  • Populate sortedOrdersPerDay upfront with fetch.

  • Then (I did not test, that's just the principle):

      List {
        ForEach(sortedOrdersPerDay, id: \.self) { ordersOfTheDay in
          Section(header: Text(ordersOfTheDay.day)) {
            ForEach(ordersOfTheDay) { order in
				NavigationLink {
					OrderDetailView(order: order)
				} label: {
					OrderRow(order: order)
				}
            }
          }
        }
      } 

Good morning (o;

Hmm...gives me:

Generic struct 'ForEach' requires that 'ordersOfADay' conform to 'RandomAccessCollection'

Whatever that means (o;

Ah bugger...totally overlooked your line here with:

  • Populate sortedOrdersPerDay upfront with fetch.

Have to learn some more Swift than on how to achieve that (o;