Project 4: Habit Tracker with Streaks and Date Logic

iOS App Development with Swift and SwiftUI: 13 Projects · More Real-World iOS Projects · 12 min read · Updated

Counting a streak

  1. Each completed day is stored as a text key in a set.
  2. The rule first checks today. If it is not done, it starts from yesterday.
  3. It then moves back one day at a time while each day is in the set.
  4. The first gap stops the count, and that number is the streak.

Habit apps look simple, but they teach one of the hardest parts of real software: dates. What is "today"? What is "yesterday" when the phone changes time zone? This project keeps the rules small and testable. Each day a habit is done is stored as a text key such as "2026-11-10", and the streak is the number of days in a row counted back from today.

Storage is deliberately plain. The habits are encoded as JSON and saved in UserDefaults, which is enough for a small list and shows you how Codable works on its own. For larger data, use SwiftData, as in the previous project.

Concepts in this project

  • Codable structs: Habit becomes JSON with JSONEncoder and back with JSONDecoder.
  • Day keys: a text such as 2026-11-10 avoids time-of-day and time zone surprises in sets and comparisons.
  • Calendar arithmetic: calendar.date(byAdding: .day, value: -1, to:) instead of subtracting 86,400 seconds, which breaks on daylight saving days.
  • Streak rule: count back from today. If today is not done yet, start from yesterday so the streak is not lost before the day ends.
  • Injected dependencies: the functions take today and calendar parameters, so tests can use a fixed date and a fixed time zone.
  • didSet persistence: the store saves whenever habits changes.

Create the project

  1. In Xcode choose File > New > Project > iOS > App. Set Interface to SwiftUI, Language to Swift, and Testing System to Swift Testing. Set the minimum deployment to iOS 17, because the code uses @Observable. Name the product Habits.
  2. Delete the default ContentView.swift and the default @main file, then add the files below.
Habits/
  HabitApp.swift     @main
  Habit.swift        model, DayKey, streak rule
  HabitStore.swift   @Observable store saved as JSON
  HabitView.swift    list, add, tick today
HabitsTests/
  HabitTests.swift

The code

`Habit.swift`

import Foundation

struct Habit: Identifiable, Codable, Equatable {
    var id = UUID()
    var name: String
    var days: Set<String> = []   // one "2026-11-10" text per day that was done
}

enum DayKey {
    static func key(for date: Date, calendar: Calendar = .current) -> String {
        let parts = calendar.dateComponents([.year, .month, .day], from: date)
        return String(format: "%04ld-%02ld-%02ld", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0)
    }
}

extension Habit {
    func isDone(on date: Date, calendar: Calendar = .current) -> Bool {
        days.contains(DayKey.key(for: date, calendar: calendar))
    }

    // Days in a row, counting back from today. If today is not done yet, the streak is
    // still alive when yesterday is done, so the user does not lose it before the day ends.
    func currentStreak(today: Date = .now, calendar: Calendar = .current) -> Int {
        var day = today
        if !isDone(on: day, calendar: calendar) {
            guard let yesterday = calendar.date(byAdding: .day, value: -1, to: day) else { return 0 }
            day = yesterday
        }
        var count = 0
        while isDone(on: day, calendar: calendar) {
            count += 1
            guard let previous = calendar.date(byAdding: .day, value: -1, to: day) else { break }
            day = previous
        }
        return count
    }
}

`HabitStore.swift`

import Foundation
import Observation

@Observable
final class HabitStore {
    private let defaults: UserDefaults
    private let storageKey = "habits.v1"

    var habits: [Habit] {
        didSet { save() }
    }

    init(defaults: UserDefaults = .standard) {
        self.defaults = defaults
        if let data = defaults.data(forKey: "habits.v1"),
           let saved = try? JSONDecoder().decode([Habit].self, from: data) {
            habits = saved
        } else {
            habits = []
        }
    }

    func add(name: String) {
        let clean = name.trimmingCharacters(in: .whitespaces)
        guard !clean.isEmpty else { return }
        habits.append(Habit(name: clean))
    }

    func toggleToday(_ habit: Habit, today: Date = .now) {
        guard let index = habits.firstIndex(where: { $0.id == habit.id }) else { return }
        let key = DayKey.key(for: today)
        if habits[index].days.contains(key) {
            habits[index].days.remove(key)
        } else {
            habits[index].days.insert(key)
        }
    }

    func delete(at offsets: IndexSet) {
        habits.remove(atOffsets: offsets)
    }

    private func save() {
        if let data = try? JSONEncoder().encode(habits) {
            defaults.set(data, forKey: storageKey)
        }
    }
}

`HabitView.swift`

import SwiftUI

struct HabitView: View {
    @State private var store = HabitStore()
    @State private var newName = ""

    var body: some View {
        NavigationStack {
            List {
                Section {
                    HStack {
                        TextField("New habit, e.g. Read 10 pages", text: $newName)
                            .onSubmit(add)
                        Button("Add", action: add)
                    }
                }
                Section {
                    if store.habits.isEmpty {
                        Text("No habits yet. Add one above.")
                            .foregroundStyle(.secondary)
                    }
                    ForEach(store.habits) { habit in
                        HStack {
                            VStack(alignment: .leading) {
                                Text(habit.name)
                                Text("Streak: \(habit.currentStreak()) day(s)")
                                    .font(.caption)
                                    .foregroundStyle(.secondary)
                            }
                            Spacer()
                            Button {
                                store.toggleToday(habit)
                            } label: {
                                Image(systemName: habit.isDone(on: .now) ? "checkmark.circle.fill" : "circle")
                                    .font(.title2)
                            }
                            .buttonStyle(.plain)
                            .accessibilityLabel(habit.isDone(on: .now) ? "Done today" : "Mark done today")
                        }
                    }
                    .onDelete(perform: store.delete)
                }
            }
            .navigationTitle("Habits")
        }
    }

    private func add() {
        store.add(name: newName)
        newName = ""
    }
}

`HabitApp.swift`

import SwiftUI

@main
struct HabitApp: App {
    var body: some Scene {
        WindowGroup {
            HabitView()
        }
    }
}

`HabitTests.swift (in the tests target)`

import Testing
import Foundation
@testable import Habits

struct HabitTests {
    // A fixed calendar and time zone so the tests give the same result everywhere.
    private var calendar: Calendar {
        var calendar = Calendar(identifier: .gregorian)
        calendar.timeZone = TimeZone(identifier: "UTC")!
        return calendar
    }

    private func date(_ year: Int, _ month: Int, _ day: Int) -> Date {
        calendar.date(from: DateComponents(year: year, month: month, day: day, hour: 12))!
    }

    private func habit(done days: [Date]) -> Habit {
        Habit(name: "Read", days: Set(days.map { DayKey.key(for: $0, calendar: calendar) }))
    }

    @Test func threeDaysInARowGiveStreakThree() {
        let item = habit(done: [date(2026, 11, 8), date(2026, 11, 9), date(2026, 11, 10)])
        #expect(item.currentStreak(today: date(2026, 11, 10), calendar: calendar) == 3)
    }

    @Test func streakSurvivesUntilTodayIsDone() {
        let item = habit(done: [date(2026, 11, 8), date(2026, 11, 9)])
        #expect(item.currentStreak(today: date(2026, 11, 10), calendar: calendar) == 2)
    }

    @Test func aGapBreaksTheStreak() {
        let item = habit(done: [date(2026, 11, 6), date(2026, 11, 10)])
        #expect(item.currentStreak(today: date(2026, 11, 10), calendar: calendar) == 1)
    }

    @Test func noDaysMeansNoStreak() {
        let item = habit(done: [])
        #expect(item.currentStreak(today: date(2026, 11, 10), calendar: calendar) == 0)
    }

    @Test func keyIsPaddedAndReadable() {
        #expect(DayKey.key(for: date(2026, 3, 5), calendar: calendar) == "2026-03-05")
    }
}

Walkthrough

Habit stores its completed days in a Set<String>. A set gives fast lookups and cannot hold the same day twice. DayKey.key(for:) builds the text from the year, month and day parts of a date. Because it uses only those three parts, two moments on the same calendar day produce the same key.

The streak function is the heart of the project. It first checks whether today is done. If not, it moves to yesterday, so a streak of 5 stays 5 until midnight passes without a tick. Then a loop counts days while each one is in the set, moving one day back each time. The loop stops at the first gap.

Notice the default parameters today: Date = .now and calendar: Calendar = .current. In the app you never pass them. In tests you pass a fixed calendar in UTC and fixed dates, so the result is the same on every machine and in every time zone. This is the standard way to make time-dependent code testable.

HabitStore loads in its initialiser and saves in didSet. didSet does not run during initialisation, which avoids saving the same data right after loading it. toggleToday finds the habit by id, then inserts or removes today's key. The view reads habit.isDone(on: .now) to choose the filled or empty circle.

The tests cover the main rules: three days in a row, a streak that survives until today is done, a gap that breaks the streak, no days at all, and the padded key format. Five small tests like this catch almost every date bug before a user does.

How it works

  • The view shows each habit with its streak and a circle button for today.
  • Tapping the circle calls toggleToday, which edits the set of day keys.
  • didSet on habits encodes the list to JSON and writes it to UserDefaults.
  • On the next launch the store decodes the JSON and the habits come back.

Expected output

The screen shows a text box with an Add button and the message "No habits yet." Add "Read 10 pages": it appears with "Streak: 0 day(s)". Tap the circle: it fills and the streak shows 1. Tap again: it empties and the streak returns to 0. Close and reopen the app: the habit is still there. Swipe to delete a habit. The five tests pass.

Your task

  1. Build the app, add two habits and tick one.
  2. Change your Simulator date to tomorrow, reopen the app and see the streak still counts.
  3. Add a longest-streak value and a test for it.
  4. Move the storage to SwiftData and keep the same tests for the streak rule.

How to check it worked

  • A streak does not break before the day ends.
  • Tests use a fixed calendar and time zone.
  • You can explain why subtracting 86,400 seconds is not safe.

Next, try the same idea on another platform with the Android Development with Kotlin course, or go deeper on iOS with the Advanced iOS Development course.

Frequently asked questions

Why store days as text?

A text such as 2026-11-10 means a whole calendar day. Dates carry a time of day, which makes equality checks unreliable.

Why not subtract 86,400 seconds for yesterday?

Some days have 23 or 25 hours because of daylight saving. Calendar arithmetic handles this correctly.

When should I use SwiftData instead of UserDefaults?

UserDefaults is for small settings and short lists. Use SwiftData when you have many records, need queries or want relationships.