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.
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.
| Concern | Django ModelForm | Android (Chapter 6) | iOS (this chapter) |
|---|---|---|---|
| Create vs update | Two URLs, one form class | One route, itemId 0 = new | One view, item: Item?, nil = new |
| Where the typed text lives | The request and form object | A FormUiState in a view model | An ItemDraft struct in @State |
| Field to state | Form field | value + onValueChange | A binding: $draft.title |
| Validation | is_valid() | Derived flags on the state | Derived properties on the draft |
| Cancel | Do not save | Leave without saving | Dismiss: nothing was written, because the draft is a copy |
| Presented as | A page | A navigation destination | A 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.
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.
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.)
Reading the Form
- Labels change with the type.
labelsis recomputed every timedraft.typeNamechanges, 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.typeNameis aString?, and aPicker's selection must match its rows'tagtype exactly, so each row is taggedOptional(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.).numberPadshows 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
createdAtalone, 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 intosave. - New items are not inserted until Save.
Item(title:type:)is only created insidesave, andCatalogueRepository.saveinserts 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.
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.
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
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.
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.
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.
Chapter 6 Quick Reference
- One form for add and edit:
ItemFormView(item: Item?);nilmeans 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 withonChange(of:);.keyboardType(.numberPad) - Segmented
Pickerover an optional: tag each row withOptional(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;
createdAtis kept by editing the live object
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.