Skip to Content
Course content

212: Building a Habit Tracker with SwiftData and Charts

Click on the "Edit" button in the top corner of the screen to edit your slide content.

When you first start combining SwiftData with Swift Charts, you'll likely fall into a trap I did: thinking you need to build a "Data Transformer" layer. You'll feel the urge to write a complex ViewModel that fetches your habit records, maps them into a separate ChartPoint struct, and manages a published array of those points. You tell yourself it's "better architecture" to keep the database models away from the UI.

Here is why that's a mistake. Swift Charts is designed to work with any collection that conforms to RandomAccessCollection. Since SwiftData's @Query provides you with a dynamic array of models, adding a manual transformation layer just introduces a synchronization headache. You'll find yourself fighting with Combine or AsyncSequence just to make sure the chart updates when a user checks off a habit. It's a lot of boilerplate for zero actual gain.

Stop building manual data mappers for your charts

If we're building a habit tracker, we have a HabitEntry model. You might be tempted to do something like this:

// THE WRONG WAY: Over-engineering the data flow
struct ChartViewModel: ObservableObject {
    @Published var chartPoints: [ChartPoint] = []
    
    func updatePoints(from entries: [HabitEntry]) {
        self.chartPoints = entries.map { ChartPoint(date: $0.date, value: $0.value) }
    }
}

This is a productivity killer. You're essentially duplicating your data in memory and creating a manual bridge that you have to maintain. If you add a new property to HabitEntry, you now have to update the model, the ChartPoint struct, and the mapping function. I've spent far too many hours debugging "why isn't the chart updating" only to realize the mapper function didn't fire. Don't do it.

Connecting SwiftData directly to the Chart axis

The better way is to let the Chart view iterate over your @Query results directly. Swift Charts is incredibly efficient at handling this. You just need to tell the chart which property of your model maps to which axis.

Let's look at a real implementation for a "Daily Reading" habit tracker. We want a bar chart showing how many pages were read over the last week.

import SwiftUI
import SwiftData
import Charts

struct HabitChartView: View {
    // We fetch the entries directly in the view
    @Query(sort: \HabitEntry.date) var entries: [HabitEntry]

    var body: some View {
        Chart {
            ForEach(entries) { entry in
                BarMark(
                    x: .value("Date", entry.date, unit: .day),
                    y: .value("Pages", entry.pageCount)
                )
                .foregroundStyle(.blue.gradient)
            }
        }
        .frame(height: 300)
        .padding()
    }
}

Notice how clean this is. The BarMark is taking the HabitEntry object and extracting the value on the fly. By using the unit: .day parameter in the X-axis value, Swift Charts handles the date formatting and grouping for us. You don't need to strip the time off the Date object or convert it to a string—the framework does the heavy lifting.

Handling the "Empty Day" gap in your streaks

Now, here is the professional touch. If you use the code above, you'll notice a problem: if a user misses a day and doesn't log an entry, that day simply disappears from the X-axis. Your chart will jump from Monday to Wednesday, making the "streak" look continuous when it actually has a gap. That's a lie to the user, and in a habit tracker, that's a cardinal sin.

To fix this, we don't change the data; we change the axis. By using the chartXAxis modifier with a Date scale, we can force the chart to show every single day in the range, regardless of whether there is data for it.

Chart {
    ForEach(entries) { entry in
        BarMark(
            x: .value("Date", entry.date, unit: .day),
            y: .value("Pages", entry.pageCount)
        )
    }
}
.chartXAxis {
    // This forces the axis to represent a continuous timeline
    AxisMarks(values: .stride(by: .day)) 
}
.chartXScale(domain: startDate...endDate) // Define your 7-day window here

I usually calculate startDate as Calendar.current.date(byAdding: .day, value: -7, to: .now). This ensures the user always sees a full week of their progress, creating that psychological pressure (the "don't break the chain" effect) that makes habit trackers actually work.




📋 Practical Task

Exercise: Implementing a 7-Day "Water Intake" Volume Chart

You are tasked with adding a hydration tracking feature to the app. You already have a WaterEntry model with two properties: date: Date and milliliters: Int.

Create a SwiftUI view called HydrationChartView that satisfies the following requirements:

  • Use @Query to fetch WaterEntry objects sorted by date.
  • Display a Chart using AreaMark (instead of BarMark) to show the trend of water intake.
  • The X-axis must represent the date, and the Y-axis must represent the milliliters.
  • Implement a chartXScale that dynamically limits the view to exactly the last 7 days, ensuring that days with zero entries are still visible as gaps in the area chart.
  • Add a chartYAxis label that explicitly names the unit as "mL".
Rating
0 0

There are no comments for now.

to be the first to leave a comment.