Add and Edit Form

Personal Catalogue: iOS (Swift & SwiftUI)

Course 1 ยท Chapter 6 ยท Form, Draft and Validation

So far the only way to put data in is a temporary "+" that inserts "Sample item". This chapter replaces it with the real thing: one form screen for both adding and editing, whose labels change with the item type (a book has an "Author", a CD an "Artist", a film a "Director"), with validation, and with a design that makes Cancel really discard. It also finishes two loose ends from Chapter 5: the Edit button will work, and the sample-item code is deleted.

What was run, and what was not
Nothing in this chapter was compiled or run (no Mac or Xcode here). My search confirmed from Apple's SwiftData documentation that one editor view can serve both adding and editing, with the title switching on whether a model is passed in, and that the context is saved explicitly. It also surfaced forum threads on discarding edits and a "draft" pattern. It found nothing on the number keyboard or the segmented Picker, which are from my memory, as is every API detail below.

One Form, Two Jobs

Adding and editing are the same screen with different starting values, which a web developer will recognise from Django's ModelForm. Apple's own SwiftData sample does the same: a single editor view whose title is "Add" or "Edit" depending on whether it was given an item.

ConcernDjango ModelFormAndroid (Chapter 6)iOS (this chapter)
Create vs updateTwo URLs, one form classOne route, itemId 0 = newOne view, item: Item?, nil = new
Where the typed text livesThe request and form objectA FormUiState in a view modelAn ItemDraft struct in @State
Field to stateForm fieldvalue + onValueChangeA binding: $draft.title
Validationis_valid()Derived flags on the stateDerived properties on the draft
CancelDo not saveLeave without savingDismiss: nothing was written, because the draft is a copy
Presented asA pageA navigation destinationA sheet with its own navigation bar

Why a Draft Instead of Editing the Item Directly

SwiftUI makes it tempting to bind a text field straight to the model: with @Bindable var item: Item, TextField("Title", text: $item.title) edits the stored object on every keystroke. That is the least code, and it has a real flaw for a form with a Cancel button: the edit has already happened. My search found Apple-forum threads asking exactly this ("SwiftData and discarding unsaved changes", and one that "sandboxes" edits in a separate model context), and Apple's documentation notes that autosave is a setting, not a certainty, so whether an abandoned edit survives depends on when the context saves. Rather than depend on that, this chapter edits a copy: a plain struct, ItemDraft, which is only written into the model when the user taps Save. Cancel is then trivially correct, because there is nothing to undo. It is the same idea as the Android course's FormUiState.

Step 1: Labels That Follow the Type

Put this in FieldLabels.swift. It matches on the seeded type names from Chapter 3, which is fine for a fixed list.

struct FieldLabels { let creator: String let format: String } func labels(for typeName: String?) -> FieldLabels { switch typeName { case "Book": return FieldLabels(creator: "Author", format: "Format (hardcover, paperback...)") case "CD": return FieldLabels(creator: "Artist", format: "Format (album, single...)") case "DVD", "Blu-ray": return FieldLabels(creator: "Director", format: "Edition or region code") default: return FieldLabels(creator: "Creator", format: "Format") } }

Step 2: The Draft

The draft holds every field as text or a simple value, and computes its own validity. Two choices carry over from Android. The year is held as text while it is being typed (an empty box is not a number) and converted on save. And the existing tag names travel with the draft: Chapter 7 adds the controls to change them, but until then an edit must preserve them, because the repository's save replaces an item's tags with the names it is given.

import Foundation struct ItemDraft { var title = "" var creator = "" var formatDetail = "" var yearText = "" var notes = "" var typeName: String? var tagNames: [String] = [] /// A blank draft, for a new item. init() {} /// A copy of an existing item's fields, for editing. init(item: Item) { title = item.title creator = item.creator formatDetail = item.formatDetail yearText = item.releaseYear.map(String.init) ?? "" notes = item.notes typeName = item.type?.name tagNames = item.sortedTags.map(\.name) } var titleError: Bool { title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } var yearError: Bool { guard !yearText.isEmpty else { return false } let latest = Calendar.current.component(.year, from: .now) + 1 guard let year = Int(yearText) else { return true } return !(1000...latest).contains(year) } var isValid: Bool { !titleError && !yearError && typeName != nil } }

Because ItemDraft is plain Swift with no UI and no database in it, Chapter 10 can test every one of those rules in milliseconds. That is the practical benefit of keeping the logic out of the view.

Step 3: The Form

ItemFormView takes an optional item. Its draft is created in init from that item (or blank), stored in @State so it survives redraws, and each field binds to a piece of it with $draft.something. The whole thing is wrapped in its own NavigationStack: a sheet is a separate presentation, so it needs its own navigation bar for the Cancel and Save buttons. (This is not the nested-stack problem from Chapter 5; that was a stack inside a screen that was already inside one.)

import SwiftUI import SwiftData struct ItemFormView: View { let item: Item? // nil = adding a new item @Environment(\.modelContext) private var context @Environment(\.dismiss) private var dismiss @Query(sort: \ItemType.sortOrder) private var types: [ItemType] @State private var draft: ItemDraft @State private var showErrors = false init(item: Item?) { self.item = item _draft = State(initialValue: item.map(ItemDraft.init(item:)) ?? ItemDraft()) } var body: some View { let labels = labels(for: draft.typeName) NavigationStack { Form { Section("Type") { Picker("Type", selection: $draft.typeName) { ForEach(types) { type in Text(type.name).tag(Optional(type.name)) } } .pickerStyle(.segmented) } Section { TextField("Title (required)", text: $draft.title) .textInputAutocapitalization(.words) } footer: { if showErrors && draft.titleError { Text("Please enter a title").foregroundStyle(.red) } } Section { TextField(labels.creator, text: $draft.creator) .textInputAutocapitalization(.words) TextField(labels.format, text: $draft.formatDetail) } Section { TextField("Year (optional)", text: $draft.yearText) .keyboardType(.numberPad) } footer: { if showErrors && draft.yearError { Text("Enter a four-digit year").foregroundStyle(.red) } } Section("Notes") { TextField("Notes", text: $draft.notes, axis: .vertical) .lineLimit(3...6) } } .navigationTitle(item == nil ? "Add Item" : "Edit Item") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } ToolbarItem(placement: .confirmationAction) { Button("Save") { save() } } } .onChange(of: draft.yearText) { _, newValue in let digits = String(newValue.filter(\.isNumber).prefix(4)) if digits != newValue { draft.yearText = digits } } .task(id: types.count) { if draft.typeName == nil { draft.typeName = types.first?.name } } } } private func save() { guard draft.isValid else { showErrors = true return } guard let type = types.first(where: { $0.name == draft.typeName }) else { return } let target = item ?? Item(title: draft.title, type: type) target.title = draft.title.trimmingCharacters(in: .whitespacesAndNewlines) target.creator = draft.creator.trimmingCharacters(in: .whitespacesAndNewlines) target.formatDetail = draft.formatDetail.trimmingCharacters(in: .whitespacesAndNewlines) target.releaseYear = Int(draft.yearText) target.notes = draft.notes.trimmingCharacters(in: .whitespacesAndNewlines) target.type = type do { try CatalogueRepository(context: context).save(target, tagNames: draft.tagNames) dismiss() } catch { print("Save failed: \(error)") // Chapter 9 shows this to the user } } } #Preview("Add") { ItemFormView(item: nil).modelContainer(PreviewData.container) } #Preview("Edit") { ItemFormView(item: PreviewData.sampleItem).modelContainer(PreviewData.container) }

Reading the Form

  • Labels change with the type. labels is recomputed every time draft.typeName changes, so tapping a different segment relabels the creator and format fields at once while the text typed stays: the same behaviour as the Android form.
  • The picker's tag. draft.typeName is a String?, and a Picker's selection must match its rows' tag type exactly, so each row is tagged Optional(type.name). This mismatch (a non-optional tag for an optional selection) is a classic reason a picker looks right and selects nothing.
  • Errors appear after the first Save, through showErrors, so the form does not shout at someone who has not started typing. They show in the section footer, the standard place for a hint under a group of fields.
  • The year filter. onChange(of:) strips anything that is not a digit and caps the length at four. (The two-parameter closure is the iOS 17 form.) .numberPad shows a digits-only keyboard, but it does not stop a pasted letter, which is why the filter exists.
  • Editing does not touch what the form does not show. An edit changes the existing object's fields and leaves createdAt alone, so the "Added" date is preserved without any extra code: here the live object does for free what the Android version had to remember to carry. The tags are preserved because the draft carries their names back into save.
  • New items are not inserted until Save. Item(title:type:) is only created inside save, and CatalogueRepository.save inserts it (Chapter 3), so pressing Cancel on an Add form leaves no trace.

Step 4: Wiring and Clean-up

Present the form as a sheet from both places that need it, and delete the temporary code.

// ListView.swift @State private var showAdd = false // add this // delete: @Environment(\.modelContext) private var context (no longer used) // delete: the whole addSampleItem() function Button("Add", systemImage: "plus") { showAdd = true } // was { addSampleItem() } // next to .navigationTitle(...) on the VStack: .sheet(isPresented: $showAdd) { ItemFormView(item: nil) } // DetailView.swift @State private var showEdit = false Button("Edit", systemImage: "pencil") { showEdit = true } // was { /* Chapter 6 */ } // next to .confirmationDialog(...): .sheet(isPresented: $showEdit) { ItemFormView(item: item) }

Run it: tap "+", pick CD (the label becomes "Artist"), type a title, and Save. Open the item, tap the pencil, change the title and Save: the detail screen updates itself with no refresh code, because the item is an observable object and the view reads it. Try Save with an empty title to see the error, and Cancel after typing to confirm nothing is saved.

Compare with the Android course
In Personal Catalogue: Android (Kotlin & Compose) Chapter 6 the form's state lived in a ViewModel and had to survive rotation, and the edit had to carry createdAt and the tag ids through by hand. The iOS draft is simpler (a struct in @State) and editing a live object keeps untouched fields automatically. The price is the one in this chapter's opening: because the model is live, you must choose to edit a copy, or Cancel will not mean cancel. The validation rules and the per-type labels are identical in the two courses.

Challenges

Exercise 1

Add FieldLabels, ItemDraft and ItemFormView, make the wiring edits, and remove the temporary code. Add one item of each type and write down the label of the creator field for each. Then edit one and confirm its "Added" date did not change.

๐Ÿ“„ View solution
Exercise 2

Make the year error appear immediately (not just after Save), and make the title field ignore leading spaces as the user types. Say which type each change belongs in (ItemDraft, ItemFormView or the repository) and why.

๐Ÿ“„ View solution
Exercise 3

Test the alternative the chapter argued against. In a copy of the form, bind a field straight to the model with @Bindable var item: Item and TextField("Title", text: $item.title), with a Cancel button that only dismisses. Edit an item's title, press Cancel, then check the list and quit and relaunch the app. Record what happened each time and the iOS version.

๐Ÿ“„ View solution

Chapter 6 Quick Reference

  • One form for add and edit: ItemFormView(item: Item?); nil means new; title "Add Item" or "Edit Item"
  • Edit a draft copy (@State private var draft: ItemDraft), written to the model only on Save, so Cancel discards for free
  • Create the state in init: _draft = State(initialValue: ...)
  • Bindings: TextField("Title", text: $draft.title); year as text, filtered with onChange(of:); .keyboardType(.numberPad)
  • Segmented Picker over an optional: tag each row with Optional(value)
  • Validation as derived properties on the draft; show errors after the first Save, in section footers
  • A sheet needs its own NavigationStack; Cancel is .cancellationAction, Save is .confirmationAction
  • Edits must preserve what the form does not show: tags travel in the draft; createdAt is kept by editing the live object
Not Yet Verified
Checked (one web search on 2026-11-19): that Apple's SwiftData documentation shows one editor view for adding and editing, titled by whether a model was passed in, and calls save() explicitly because autosave is a setting; that Apple-forum threads discuss discarding unsaved edits and sandboxing edits in a separate model context; that a blog describes a "draft" pattern in which discarding is just dismissal; and that Hacking with Swift's book dismisses a SwiftData add form after saving.
Not checked, from general knowledge, and the search found nothing on the keyboard or Picker: .keyboardType(.numberPad); the segmented Picker and the Optional(...) tag rule; TextField(axis: .vertical) and .lineLimit(3...6); .textInputAutocapitalization; onChange(of:) with two parameters; Section with a footer closure; .task(id:); the toolbar placements .cancellationAction and .confirmationAction; that creating an Item with a type before it is inserted into the context is acceptable (Chapter 3 recommended inserting before assigning relationships; if Xcode or the console complains, create the item with type: nil and assign it after save inserts); the claim in the chapter's opening about when an abandoned live edit would survive; and all code, none of which was compiled. I did not consult Apple's reference pages for these APIs.
Coming next
Personal Catalogue: iOS (Swift & SwiftUI) 7 adds tags: a managed list that never allows "Web Development" and "web development" to coexist, suggestions while typing, tag chips, and the many-to-many writes that replace the preserved tag names used in this chapter.