-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Optionals
-
Section 4: Object-Oriented and Value Types
-
Section 5: Memory Management
-
Section 6: Generics and Error Handling
-
Section 7: Concurrency
-
Section 8: Working with Collections
-
Section 9: Codable and Data Handling
-
Section 10: Protocol-Oriented Programming
-
Section 11: Testing and Tooling
-
Section 12: Practical Projects
-
Section 13: Interview Practice
-
Section 14: More Practice Exercises
-
Section 15: More Standard Library
-
Section 16: Advanced Concurrency
-
Section 17: Foundation Framework Deep Dive
-
Section 18: URLSession and Networking Deep Dive
-
Section 19: Combine Framework
-
Section 20: SwiftUI Fundamentals for Swift Developers
-
Section 21: Server-Side Swift with Vapor
-
Section 22: Swift Package Manager Deep Dive
-
Section 23: Swift Concurrency Deep Dive
-
Section 24: More Language Features
-
Section 25: Error Handling Deep Dive
-
Section 26: Testing Deep Dive
-
Section 27: Data Structures and Algorithms in Swift
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Swift Macros (Swift 5.9+)
-
Section 31: Property Wrappers Ecosystem
-
Section 32: Swift Interop Deep Dive
-
Section 33: iOS App Architecture Patterns
-
Section 34: Performance and Debugging
-
Section 35: App Distribution and CI/CD
-
Section 36: More Practical Projects
-
Section 37: SwiftData and Persistence
-
Section 38: More Design Patterns
-
Section 39: More Review and Practice
-
Section 40: More Foundation Deep Dive
-
Section 41: Advanced Collections in Swift
-
Section 42: Advanced Generics Practice
-
Section 43: UIKit for Legacy and Hybrid Apps
-
Section 44: watchOS and visionOS Development Basics
-
Section 45: More Networking Patterns
-
Section 46: More Testing Practice
-
Section 47: Accessibility in Swift Apps
-
Section 48: Localization
-
Section 49: More Practical Projects Round 2
-
Section 50: Swift Charts Framework
-
Section 51: More Interview and Algorithm Practice
-
Section 52: Final Practice and Mastery
-
Section 53: Swift Compiler and Build System
-
Section 54: More Concurrency Practice
-
Section 55: App Store Guidelines and Review
-
Section 56: More Design and Architecture
212: Building a Habit Tracker with SwiftData and Charts
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
@Queryto fetchWaterEntryobjects sorted by date. - Display a
ChartusingAreaMark(instead ofBarMark) to show the trend of water intake. - The X-axis must represent the date, and the Y-axis must represent the
milliliters. - Implement a
chartXScalethat 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
chartYAxislabel that explicitly names the unit as "mL".
There are no comments for now.