Build iOS Todo app with swiftdata
- User
Build iOS Todo app with swiftdata
Assistant
Okay, let's build a simple iOS Todo app using SwiftUI and SwiftData.
We'll cover:
- Setting up a new project with SwiftData.
- Defining the Todo item model.
- Displaying the list of Todos using
@Query. - Adding new Todos.
- Marking Todos as complete.
- Deleting Todos.
Project Setup
- Open Xcode.
- Create a new project (
File->New->Project...). - Select
iOS->Appand clickNext. - Product Name:
SwiftDataTodo(or whatever you like). - Interface:
SwiftUI. - Life Cycle:
SwiftUI App. - Storage: Make sure
Use SwiftDatais checked. (This is the key step for automatic setup). - Click
Next, choose where to save your project, and clickCreate.
Xcode will create a basic project with SwiftData boilerplate ready.
1. Define the Todo Item Model
Create a new Swift file (
File->New->File...->iOS->Swift File). Name itTodoItem.swift.Replace the content with the following:
import Foundation import SwiftData @Model final class TodoItem { var text: String var isComplete: Bool var creationDate: Date // Good practice to add a timestamp init(text: String, isComplete: Bool = false, creationDate: Date = Date.now) { self.text = text self.isComplete = isComplete self.creationDate = creationDate } }@Model: This macro makesTodoItemeligible for storage by SwiftData. It automatically generates the necessary schema and accessors.final class: SwiftData models must beclasstypes, andfinalis generally recommended for performance.- Properties: We define the data for each todo item (
text,isComplete,creationDate). init: A simple initializer.isCompleteandcreationDatehave default values.
2. Display the List of Todos
Open
ContentView.swift.import SwiftUI import SwiftData struct ContentView: View { // Use @Query to fetch TodoItem objects // Sort by creationDate to show newest first (or oldest first, your choice) @Query(sort: \TodoItem.creationDate, order: .reverse) private var todos: [TodoItem] // Access the SwiftData model context from the environment @Environment(\.modelContext) private var modelContext @State private var showingAddTodoSheet = false // State to control the add sheet var body: some View { NavigationView { // Use NavigationView for title and toolbar List { // Use ForEach with id: \.self for identifiable items when deleting ForEach(todos) { todo in // HStack for the todo item row HStack { // Toggle to mark as complete Toggle("", isOn: Bindable(todo).isComplete) .labelsHidden() // Hide the default Toggle label // Text of the todo item Text(todo.text) // Add strikethrough if complete .strikethrough(todo.isComplete) // Make text less prominent if complete .foregroundStyle(todo.isComplete ? .gray : .primary) Spacer() // Push content to the left } } // Add swipe-to-delete functionality .onDelete(perform: deleteItems) } .navigationTitle("My Todos") // Set navigation bar title .toolbar { // Add a toolbar for the "Add" button ToolbarItem(placement: .navigationBarTrailing) { Button { showingAddTodoSheet = true // Show the add sheet } label: { Label("Add Item", systemImage: "plus.circle.fill") } } } // Present the sheet for adding new todos .sheet(isPresented: $showingAddTodoSheet) { AddTodoView() // We'll create this view next // Pass the model context to the sheet's environment .environment(\.modelContext, modelContext) } } } // Function to handle deleting items private func deleteItems(offsets: IndexSet) { withAnimation { for index in offsets { let todoToDelete = todos[index] modelContext.delete(todoToDelete) // Delete the item from the context } // SwiftData automatically saves changes within a transaction like this block } } } #Preview { ContentView() // Attach the modelContainer to the preview environment // This allows the preview to use SwiftData .modelContainer(for: TodoItem.self, inMemory: true) // Use in-memory for preview }@Query: This property wrapper fetches allTodoIteminstances from the connectedmodelContext. Thesortparameter orders the results.@Environment(\.modelContext): This accesses the SwiftData context that was provided to the environment (we'll see where this is set up in the App file).List: Displays theTodoItemobjects fetched by@Query.ForEach: Iterates through thetodosarray. Theid: \.selfis crucial foronDeleteto work correctly.Toggle: Binds directly totodo.isComplete. When the toggle is flipped, thetodoobject'sisCompleteproperty is updated directly within the SwiftData context. SwiftData observes this change and persists it.Text: Displays thetextproperty and uses the.strikethroughmodifier based onisComplete..onDelete: Adds swipe-to-delete gesture. ThedeleteItemsfunction handles removing the item from themodelContext.NavigationViewand.toolbar: Standard SwiftUI for setting up a navigation bar with a title and an "Add" button..sheet: PresentsAddTodoViewwhenshowingAddTodoSheetis true. It passes themodelContextdown to the new view.
3. Create the Add Todo View
Create a new Swift file (
File->New->File...->iOS->SwiftUI View). Name itAddTodoView.swift.Replace the content with the following:
import SwiftUI import SwiftData struct AddTodoView: View { @Environment(\.modelContext) private var modelContext // Access the context @Environment(\.dismiss) var dismiss // Environment variable to dismiss the sheet @State private var newTodoText = "" // State for the TextField input var body: some View { NavigationView { // Use a NavigationView within the sheet Form { // Using a Form for structure TextField("Enter new todo...", text: $newTodoText) } .navigationTitle("Add New Todo") .navigationBarTitleDisplayMode(.inline) // Use inline title style .toolbar { // Cancel button ToolbarItem(placement: .navigationBarLeading) { Button("Cancel") { dismiss() // Dismiss the sheet without saving } } // Save button ToolbarItem(placement: .navigationBarTrailing) { Button("Save") { saveTodo() // Call function to save the todo } // Disable save button if text field is empty .disabled(newTodoText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) } } } } // Function to save the new todo item private func saveTodo() { // Create a new TodoItem instance let newItem = TodoItem(text: newTodoText.trimmingCharacters(in: .whitespacesAndNewlines)) // Insert the new item into the model context modelContext.insert(newItem) // SwiftData automatically saves changes made within transactions/scopes like this // Dismiss the sheet after saving dismiss() } } #Preview { AddTodoView() // Provide a model container for the preview .modelContainer(for: TodoItem.self, inMemory: true) }@Environment(\.modelContext): Accesses themodelContextpassed fromContentView.@Environment(\.dismiss): Gets a handle to dismiss the current view presentation (the sheet).@State private var newTodoText: Holds the text entered in theTextField.NavigationView&Form: Standard SwiftUI layout for input forms.TextField: Binds tonewTodoText.ToolbarItems: Buttons for "Cancel" and "Save".saveTodo(): Creates aTodoIteminstance and callsmodelContext.insert(newItem). This is how you add new objects to SwiftData..disabled(): Prevents saving an empty todo item.
4. SwiftData Setup in the App File
Open your main App file (e.g.,
SwiftDataTodoApp.swift).You likely already have this due to checking the "Use SwiftData" box during project creation, but verify it looks like this:
import SwiftUI import SwiftData @main struct SwiftDataTodoApp: App { var body: some Scene { WindowGroup { ContentView() } // Attach the modelContainer modifier to the WindowGroup // This makes the modelContext available in the environment // to all views within this window group. .modelContainer(for: TodoItem.self) } }.modelContainer(for: TodoItem.self): This is the crucial part. It tells SwiftData to create and manage the data store for objects of typeTodoItem(and any other types you list here, e.g.,[TodoItem.self, AnotherModel.self]). It makes themodelContextavailable via the environment.
Run the App!
Build and run the app on a simulator or device (
Cmd + R).You should see:
- A list with the title "My Todos".
- An Add (+) button in the top right.
- Tap the (+) button to bring up the Add New Todo sheet.
- Type a todo item and tap "Save".
- The sheet will dismiss, and the new todo will appear in the list.
- Swipe left on a todo item to reveal the "Delete" button.
- Tap the circle next to a todo to mark it as complete/incomplete.
SwiftData Concepts Used
@Model: Defines a class that SwiftData can store.ModelContainer: The core object that manages the data store (database file). Attached to theWindowGroupin the App struct.ModelContext: The environment within which you interact with your data (fetch, insert, delete, save). Accessed via@Environment(\.modelContext).@Query: A property wrapper that automatically fetches data from themodelContextand keeps your SwiftUI view updated when the data changes.modelContext.insert(_:): Adds a new model object to the context, staging it for saving.modelContext.delete(_:): Removes a model object from the context, staging it for deletion from the store.- Automatic Saving: SwiftData contexts automatically save changes periodically and when your application enters the background. For simple applications like this, you don't typically need to call a manual
save()method unless you need to force a save immediately after a specific operation outside of standard transactions (which is rare in SwiftUI + SwiftData).
This is a solid foundation for a SwiftData Todo app! You can extend it further by adding features like editing existing todos, sorting options, filtering, categories, etc.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.