DEV Community

Armaan Khan
Armaan Khan

Posted on

How to Group and Display a List by Date in SwiftUI

Problem I Faced

I was working a gym Mac app for myself, I am new to SwiftUI and Apple ecosystem. I think I might be an almost year learning swift.

Till now I was just simply working on simple projects. Now I decided atleast I have to solve me daily problem.

I need to create an app for gym where I can track my progress.

While creating I got a Issue I want to fetch the workouts and show in the form of the list, but the problem was that I want to show the workouts that I have done according to the Dates.

How did I solved

I used Swift Data to store my data locally. It generally stores the data in the flat list. To show my all workout according to date I have to convert flat list into dictioinay.

1. Converting flat list into Dictionary

I created a Computed Property to convert the flat list into dictionary.

Dictionary(grouping: workouts) { ... } is a built-in Swift tool that walks through every item in workouts, one at a time, and asks the closure: "what key should this item live under?"

{ workout in Calendar.current.startOfDay(for: workout.date) }

It takes workout.date (which might be Sept 23, 9:03 AM) and strips the time off, giving just Sept 23, 12:00 AM. This is important β€” without this step, the 9am workout and the 6pm workout would be treated as different keys (since their exact timestamps differ), and they'd never end up grouped together.

2. Two ForEachs

Here, First ForEach shorts the items in the dictionary recent as first element.

Dictionaries have no built-in order in Swift, so if you looped over .keys directly, the dates could appear in any random order, and it might change every time. That's why .sorted(by: >) is there β€” it sorts the dates newest-first (> means descending).

groupedWorkouts[date] looks up the array of workouts belonging to that day.

Top comments (0)