New

🗂️ SwiftData Tutorial for Beginners: Build a Habit Tracker

Save data on the device with SwiftData and SwiftUI: @Model classes, a model container, @Query with filters and sorting, editing with @Bindable and a one-to-many relationship.

Beginner ⏱️ ~40 minutes 🧰 Swift, SwiftUI, SwiftData (iOS 17+)
← iOS Track

What You'll Build in This SwiftData Tutorial

This SwiftData tutorial builds a small Habit Tracker: add habits, check in once a day, rename or archive a habit, and swipe to delete. Everything is saved on the device, so your habits are still there after you quit and reopen the app. Along the way you will use every SwiftData piece a beginner needs: @Model, .modelContainer, modelContext, @Query, #Predicate, @Bindable and a relationship between two models.

SwiftData is Apple's modern way to store app data, introduced with iOS 17. Our Notes app tutorial uses Core Data, which needs a model editor file and more setup. With SwiftData, your Swift classes are the schema.

Prerequisites

  • Xcode with a new iOS App project using SwiftUI, with a deployment target of iOS 17 or later. Choose None for Storage when you create the project; we will add SwiftData by hand so you see every step.
  • Basic SwiftUI: views, @State, List and ForEach. The Swift & SwiftUI cheat sheet is a quick refresher.
  • Helpful: the SwiftUI NavigationStack tutorial, since the app pushes a detail screen with navigationDestination.

Build the Habit Tracker with SwiftData Step by Step

1 Define the models with @Model

Create Models.swift. The @Model macro turns a normal Swift class into a persistent model: SwiftData stores every stored property and tracks changes for you. A habit has many check-ins, so we add a one-to-many relationship. The .cascade delete rule removes a habit's check-ins when the habit is deleted.

// Models.swift
import Foundation
import SwiftData

@Model
final class Habit {
    var name: String
    var createdAt: Date
    var isArchived: Bool

    @Relationship(deleteRule: .cascade, inverse: \CheckIn.habit)
    var checkIns: [CheckIn] = []

    init(name: String, createdAt: Date = .now, isArchived: Bool = false) {
        self.name = name
        self.createdAt = createdAt
        self.isArchived = isArchived
    }
}

@Model
final class CheckIn {
    var date: Date
    var habit: Habit?

    init(date: Date = .now) {
        self.date = date
    }
}

Models must be classes, and every stored property needs a default value or must be set in init. Optional, Codable and enum properties are supported too.

2 Create the model container

The model container is the database. Attach it once, at the app's root scene, with the .modelContainer(for:) modifier. SwiftData creates the store file the first time the app runs and puts a model context into the SwiftUI environment for every view below it.

// HabitTrackerApp.swift
import SwiftUI
import SwiftData

@main
struct HabitTrackerApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .modelContainer(for: [Habit.self, CheckIn.self])
    }
}

3 Show and add habits with @Query and insert

@Query fetches models and refreshes the view whenever the data changes. Here it shows only habits that are not archived, newest first. To add a habit, create it and call modelContext.insert(_:). To delete, call modelContext.delete(_:).

// ContentView.swift
import SwiftUI
import SwiftData

struct ContentView: View {
    @Environment(\.modelContext) private var modelContext
    @Query(filter: #Predicate<Habit> { $0.isArchived == false },
           sort: \Habit.createdAt, order: .reverse)
    private var habits: [Habit]

    @State private var newName = ""

    var body: some View {
        NavigationStack {
            List {
                Section {
                    HStack {
                        TextField("New habit", text: $newName)
                        Button("Add", action: addHabit)
                            .disabled(trimmedName.isEmpty)
                    }
                }
                Section("My habits") {
                    ForEach(habits) { habit in
                        NavigationLink(value: habit) {
                            HabitRow(habit: habit)
                        }
                    }
                    .onDelete(perform: deleteHabits)
                }
            }
            .navigationTitle("Habits")
            .navigationDestination(for: Habit.self) { habit in
                HabitDetailView(habit: habit)
            }
        }
    }

    private var trimmedName: String {
        newName.trimmingCharacters(in: .whitespaces)
    }

    private func addHabit() {
        modelContext.insert(Habit(name: trimmedName))
        newName = ""
    }

    private func deleteHabits(at offsets: IndexSet) {
        for index in offsets {
            modelContext.delete(habits[index])
        }
    }
}

struct HabitRow: View {
    let habit: Habit

    var body: some View {
        HStack {
            Text(habit.name)
            Spacer()
            Text("\(habit.checkIns.count) check-ins")
                .foregroundStyle(.secondary)
        }
    }
}

SwiftData models are Identifiable and Hashable, so they work directly with ForEach and NavigationLink(value:).

4 Edit a habit with @Bindable and add check-ins

@Bindable gives you bindings like $habit.name to a model, so a TextField or Toggle edits the stored data directly. Turning on Archived makes the habit disappear from the list in step 3, because the query filter no longer matches it.

// HabitDetailView.swift
import SwiftUI
import SwiftData

struct HabitDetailView: View {
    @Environment(\.modelContext) private var modelContext
    @Bindable var habit: Habit

    var body: some View {
        Form {
            Section("Habit") {
                TextField("Name", text: $habit.name)
                Toggle("Archived", isOn: $habit.isArchived)
            }
            Section("Check-ins") {
                Button("Check in today", action: checkIn)
                    .disabled(hasCheckedInToday)
                ForEach(sortedCheckIns) { entry in
                    Text(entry.date, format: .dateTime.day().month().year())
                }
            }
        }
        .navigationTitle(habit.name)
    }

    private var sortedCheckIns: [CheckIn] {
        habit.checkIns.sorted { $0.date > $1.date }
    }

    private var hasCheckedInToday: Bool {
        habit.checkIns.contains { Calendar.current.isDateInToday($0.date) }
    }

    private func checkIn() {
        let entry = CheckIn()
        modelContext.insert(entry)
        entry.habit = habit   // SwiftData updates habit.checkIns too (inverse)
    }
}

Because we declared the inverse in step 1, setting entry.habit also adds the entry to habit.checkIns.

5 Search with a dynamic #Predicate

A @Query filter is fixed when the view is created. To filter by something the user types, build the query in the view's initializer. localizedStandardContains does a case-insensitive search and is supported inside #Predicate.

struct HabitSearchResults: View {
    @Query private var habits: [Habit]

    init(searchText: String) {
        _habits = Query(filter: #Predicate<Habit> { habit in
            searchText.isEmpty || habit.name.localizedStandardContains(searchText)
        }, sort: \Habit.name)
    }

    var body: some View {
        List(habits) { habit in
            Text(habit.name)
        }
    }
}

// Usage: HabitSearchResults(searchText: text)
//        inside a view with .searchable(text: $text)

6 Fetch outside a view with FetchDescriptor

In a view model, a test or a helper function you cannot use @Query. Use a FetchDescriptor with the model context instead. fetchCount returns only the number, which is faster than loading every object.

func archivedHabitCount(in context: ModelContext) throws -> Int {
    let descriptor = FetchDescriptor<Habit>(
        predicate: #Predicate { $0.isArchived == true }
    )
    return try context.fetchCount(descriptor)
}

func latestHabits(in context: ModelContext) throws -> [Habit] {
    var descriptor = FetchDescriptor<Habit>(
        sortBy: [SortDescriptor(\.createdAt, order: .reverse)]
    )
    descriptor.fetchLimit = 5
    return try context.fetch(descriptor)
}

7 Preview with an in-memory container

Views that use @Query or modelContext need a container in previews too. An in-memory container starts empty every time and never touches the real store.

#Preview {
    ContentView()
        .modelContainer(for: Habit.self, inMemory: true)
}

Run the app on a simulator, add two habits, check in, then stop and relaunch the app from Xcode. Your habits and check-ins are still there.

How SwiftData Works with SwiftUI

Practice Tasks

  1. Add an "Archived" screen that uses @Query with $0.isArchived == true and lets you un-archive a habit.
  2. Add a streak computed property to Habit that counts how many days in a row (up to today) have a check-in. Computed properties are not stored, so no migration is needed.
  3. Add a Picker on the main screen to sort by name or by date, by passing a different sort descriptor to a child view's Query initializer, like in step 5.

SwiftData Quiz

Five quick questions on this tutorial.

Frequently Asked Questions

What is SwiftData?

SwiftData is Apple's framework for saving app data on the device, available from iOS 17. You describe your data with Swift classes marked @Model, and SwiftData creates the database, saves changes and keeps SwiftUI views up to date.

Is SwiftData better than Core Data?

For new SwiftUI apps that target iOS 17 or later, SwiftData is simpler: no model editor file, no NSManagedObject subclasses and a @Query property wrapper for views. Core Data still works and is the choice when you must support iOS 16 or older. SwiftData is built on the same storage technology, so the two can share a store.

Do I need to call save() in SwiftData?

Usually not. The main context that SwiftUI gives you through the modelContext environment value saves changes automatically. Call try modelContext.save() when you want to be sure data is written right away, for example before a background task or in tests.

How do I filter and sort a SwiftData query?

Pass a #Predicate and a sort key path to @Query, for example @Query(filter: #Predicate<Habit> { $0.isArchived == false }, sort: \Habit.createdAt, order: .reverse). To filter by a value that changes, build the Query in the view's initializer.

Why does my SwiftUI preview crash with SwiftData?

Views that use @Query or modelContext need a model container. Add .modelContainer(for: Habit.self, inMemory: true) to the view inside #Preview so the preview gets an empty, temporary database.

Sources

APIs checked against Apple's SwiftData and SwiftUI documentation on December 1, 2026. SwiftData requires iOS 17, macOS 14 or later.

What to Try Next

Keep learning iOS

Head back to the iOS with Swift track for the full learning path and more hands-on projects.

Back to the iOS Track