Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 46 ยท Projects

Project: A Habit Tracker

Build a habit tracker in SwiftUI: model check-ins, compute current and best streaks with calendar math, schedule reminders and chart the week. The streak engine runs here.

A habit tracker looks simple: tap a button once a day. The interesting part is the streak, the number of days in a row you kept going. Streaks sound easy until you ask the hard questions. What if today is not checked yet? What counts as a day when the user travels across time zones? What if they check in twice? The answers are all calendar math, and getting them right is what makes the app feel fair.

In this project you build a streak engine as plain Swift, which you can run and test here, then connect it to views, local notifications and a Swift Charts bar chart. Notifications and charts need a device or simulator, so those parts are read-only. You will use ideas from @Observable, notifications and charts.

The streak rules

One per day Two taps on a day count once.
Current streak Days in a row ending today or yesterday.
Best streak The longest run ever.
Grace for today Not checked yet does not break it.

A streak only breaks when a whole day passes with no check-in.

1 / 2

Step 1: the model

Do not store "streak = 5" in the habit. A stored counter goes wrong the moment a day is missed, edited or imported. Store the facts, the days on which the habit was done, and compute the streak from them.

Swift
// read-only: Models/Habit.swift
import Foundation

struct Habit: Identifiable, Codable {
    var id = UUID()
    var name: String
    var emoji: String
    var reminderHour: Int?          // 8 means 08:00; nil means no reminder
    var checkIns: Set<Date> = []    // each Date is the START of a calendar day
}

Normalizing every date to the start of its day (calendar.startOfDay(for:)) is the key trick. Two taps at 08:00 and at 21:30 become the same value, so a Set ignores the duplicate, and comparing days becomes comparing exact dates.

Step 2: calendar math

Never compute a day by subtracting 86,400 seconds. Daylight-saving changes make some days 23 or 25 hours long. Ask the Calendar: calendar.date(byAdding: .day, value: -1, to: day) always lands on the previous calendar day in that calendar's time zone.

The engine below is a stand-in for your StreakEngine. It takes the calendar as a parameter (so tests can fix the time zone) and today's date as a parameter (so tests do not depend on the real clock).

Swift The streak engine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Look at the three "current" cases. On March 10 morning the user has not checked in yet, but the streak is still 4 because the day is not over. On the 11th the whole of the 10th has passed without a check-in, so it resets to 0. That "grace for today" rule is what stops the app from showing a broken streak at 7 a.m.

Why time zones matter

If you create the Calendar with the user's current time zone, "start of day" follows where they are. Someone flying from Lisbon to New York can have a 29-hour day or lose one. Most habit apps accept that; if you need strict stability, store the day as a plain year-month-day value (a DateComponents or a string like 2026-03-07) instead of a Date. That makes a check-in belong to a calendar day forever, regardless of later time-zone changes.

Step 3: the weekly summary

Charts and progress rings need data per day. Build a small function that returns the last seven days with a done flag, oldest first.

Swift Seven days of data for a chart

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Each row has the shape a chart or a row of seven circles needs.

Step 4: the store and the views

The store holds habits, saves them with Codable (see the to-do project) and exposes actions. The real class would be @Observable:

Swift
// read-only: Store/HabitStore.swift
import Foundation
import Observation

@Observable
final class HabitStore {
    private(set) var habits: [Habit] = []
    private let engine = StreakEngine(calendar: .current)

    func toggleToday(_ habit: Habit) {
        guard let index = habits.firstIndex(where: { $0.id == habit.id }) else { return }
        let today = engine.day(.now)
        if habits[index].checkIns.contains(today) {
            habits[index].checkIns.remove(today)       // undo a mistaken tap
        } else {
            habits[index].checkIns.insert(today)
        }
        save()
    }

    func streak(of habit: Habit) -> Int {
        engine.currentStreak(checkIns: habit.checkIns, today: .now)
    }

    func best(of habit: Habit) -> Int {
        engine.bestStreak(checkIns: habit.checkIns)
    }

    private func save() { /* encode `habits` to a JSON file, as in the to-do project */ }
}

A row shows the name, the fire counter and a button that reflects today's state:

Swift
// read-only: Views/HabitRow.swift
import SwiftUI

struct HabitRow: View {
    let habit: Habit
    let streak: Int
    let isDoneToday: Bool
    let onToggle: () -> Void

    var body: some View {
        HStack {
            Text(habit.emoji).font(.largeTitle)
            VStack(alignment: .leading) {
                Text(habit.name).font(.headline)
                Label("\(streak) day streak", systemImage: "flame.fill")
                    .font(.subheadline)
                    .foregroundStyle(streak > 0 ? .orange : .secondary)
            }
            Spacer()
            Button(action: onToggle) {
                Image(systemName: isDoneToday ? "checkmark.circle.fill" : "circle")
                    .font(.title)
            }
            .buttonStyle(.plain)
            .sensoryFeedback(.success, trigger: isDoneToday)
            .accessibilityLabel(isDoneToday ? "Undo \(habit.name) for today" : "Mark \(habit.name) done")
        }
    }
}

sensoryFeedback adds a tiny haptic on check-in, and the explicit accessibilityLabel tells VoiceOver what the button does rather than reading "circle".

Step 5: a daily reminder

Local notifications need the user's permission and a trigger. Ask when it is meaningful, for example when they enable a reminder, not at first launch. A repeating calendar trigger fires every day at the chosen hour.

Swift
// read-only: Notifications/Reminders.swift
import UserNotifications

enum Reminders {
    static func schedule(for habit: Habit) async {
        guard let hour = habit.reminderHour else { return }
        let center = UNUserNotificationCenter.current()
        guard (try? await center.requestAuthorization(options: [.alert, .sound])) == true else { return }

        let content = UNMutableNotificationContent()
        content.title = "\(habit.emoji) \(habit.name)"
        content.body = "Keep your streak going today."

        var time = DateComponents()
        time.hour = hour
        let trigger = UNCalendarNotificationTrigger(dateMatching: time, repeats: true)
        let request = UNNotificationRequest(identifier: habit.id.uuidString, content: content, trigger: trigger)
        try? await center.add(request)
    }

    static func cancel(_ habit: Habit) {
        UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [habit.id.uuidString])
    }
}

Using the habit's id as the request identifier means scheduling again replaces the old reminder, and cancel can find it. Never schedule more than a handful of reminders per habit: the system keeps at most 64 pending local notifications per app.

Step 6: a chart

Swift Charts (iOS 16+) turns the weekly data into bars with almost no code:

Swift
// read-only: Views/WeekChart.swift
import SwiftUI
import Charts

struct WeekChart: View {
    let week: [DayStatus]

    var body: some View {
        Chart(week, id: \.date) { item in
            BarMark(
                x: .value("Day", item.weekday),
                y: .value("Done", item.isDone ? 1 : 0)
            )
            .foregroundStyle(item.isDone ? Color.green : Color.gray.opacity(0.3))
        }
        .chartYAxis(.hidden)
        .frame(height: 120)
        .accessibilityLabel("Check-ins for the last seven days")
    }
}

Because the chart reads from the same lastSevenDays function you already tested, the picture can only be wrong if the data is wrong.

Where to take it

  • Allow targets such as three times per week: a streak then counts weeks that met the target.
  • Add a home-screen widget that shows today's streak (Notifications, Widgets and App Intents).
  • Switch the store to SwiftData and store check-ins as a related model instead of a set of dates.
  • Test the engine with fixed calendars and dates around daylight-saving changes (Testing View Models and UI).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why store check-in days instead of a streak number?

    Streaks are derived from the facts. Recomputing from the days keeps the number correct after edits, undo or imports.
  2. 2. On March 10 at 9 a.m., the user checked in on March 6-9 but not yet today. What should the current streak be?

    The grace rule starts counting from yesterday when today is not checked, so the run of four days is still alive.
  3. 3. Why use calendar.date(byAdding: .day, value: -1, to:) instead of subtracting 86,400 seconds?

    Calendar arithmetic respects calendar days and time-zone rules; fixed seconds drift by an hour on DST changes.
  4. 4. Why normalize check-ins with startOfDay?

    Start-of-day values are equal for every moment of the day, so a Set stores each day once.

Summary

  • Store facts (check-in days) and compute streaks; never keep a counter that can drift.
  • Normalize dates to the start of the day and use Calendar for all day arithmetic.
  • Pass the calendar and today's date into the engine so tests are deterministic.
  • Current streak gives grace for an unchecked today; best streak scans sorted days for runs.
  • Schedule one repeating local notification per habit, using the habit id as identifier.
  • Feed a chart from the same tested function that supplies the row data.

Next: Project: An Expense Tracker