Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash-preview-04-17· GoogleHugging Face LMArena Human Preference 140K

Build iOS Todo app with swiftdata

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-3-5-haiku-20241022’s answer.
  1. User

    Build iOS Todo app with swiftdata

  2. Gemini Assistant

    Okay, let's build a simple iOS Todo app using SwiftUI and SwiftData.

    We'll cover:

    1. Setting up a new project with SwiftData.
    2. Defining the Todo item model.
    3. Displaying the list of Todos using @Query.
    4. Adding new Todos.
    5. Marking Todos as complete.
    6. Deleting Todos.

    Project Setup

    1. Open Xcode.
    2. Create a new project (File -> New -> Project...).
    3. Select iOS -> App and click Next.
    4. Product Name: SwiftDataTodo (or whatever you like).
    5. Interface: SwiftUI.
    6. Life Cycle: SwiftUI App.
    7. Storage: Make sure Use SwiftData is checked. (This is the key step for automatic setup).
    8. Click Next, choose where to save your project, and click Create.

    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 it TodoItem.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 makes TodoItem eligible for storage by SwiftData. It automatically generates the necessary schema and accessors.
    • final class: SwiftData models must be class types, and final is generally recommended for performance.
    • Properties: We define the data for each todo item (text, isComplete, creationDate).
    • init: A simple initializer. isComplete and creationDate have 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 all TodoItem instances from the connected modelContext. The sort parameter 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 the TodoItem objects fetched by @Query.
    • ForEach: Iterates through the todos array. The id: \.self is crucial for onDelete to work correctly.
    • Toggle: Binds directly to todo.isComplete. When the toggle is flipped, the todo object's isComplete property is updated directly within the SwiftData context. SwiftData observes this change and persists it.
    • Text: Displays the text property and uses the .strikethrough modifier based on isComplete.
    • .onDelete: Adds swipe-to-delete gesture. The deleteItems function handles removing the item from the modelContext.
    • NavigationView and .toolbar: Standard SwiftUI for setting up a navigation bar with a title and an "Add" button.
    • .sheet: Presents AddTodoView when showingAddTodoSheet is true. It passes the modelContext down to the new view.

    3. Create the Add Todo View

    Create a new Swift file (File -> New -> File... -> iOS -> SwiftUI View). Name it AddTodoView.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 the modelContext passed from ContentView.
    • @Environment(\.dismiss): Gets a handle to dismiss the current view presentation (the sheet).
    • @State private var newTodoText: Holds the text entered in the TextField.
    • NavigationView & Form: Standard SwiftUI layout for input forms.
    • TextField: Binds to newTodoText.
    • ToolbarItems: Buttons for "Cancel" and "Save".
    • saveTodo(): Creates a TodoItem instance and calls modelContext.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 type TodoItem (and any other types you list here, e.g., [TodoItem.self, AnotherModel.self]). It makes the modelContext available 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 the WindowGroup in 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 the modelContext and 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.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.