π Day 3 β Adding and Deleting Items with SwiftData
Yesterday, I built a simple list of saved wishes using SwiftData.
But the list was static β I couldnβt add or remove anything.
Today, I learned how to insert new data and delete existing data using SwiftData and SwiftUI.
It turned out to be super easy!
β Adding New Items
I added a β+β button in the navigation bar.
When tapped, it shows an alert with a text field to enter a new wish.
Then I insert it into the database using viewContext.insert().@State private var isAlertShowing = false@State private var title = ""
.toolbar { ToolbarItem(placement: .navigationBarTrailing) { Button { isAlertShowing.toggle() } label: { Image(systemName: "plus") .imageScale(.large) } }}.alert("Add Wish Item", isPresented: $isAlertShowing) { TextField("Enter Wish", text: $title) Button("Save") { viewContext.insert(Wish(name: title)) title = "" }}
π Notes
viewContextcomes from@Environment(\.modelContext)Once inserted, the
@Queryproperty updates automatically β no manual reload needed
π Deleting Items with Swipe Actions
SwiftUI makes deleting really simple.
I just added .swipeActions on each row:ForEach(items) { item in Text(item.name) .font(.subheadline) .padding(.vertical, 8) .swipeActions { Button("Delete", role: .destructive) { viewContext.delete(item) } }}
As soon as you delete it from the viewContext, the UI list updates instantly.
β‘ Showing a Count in Toolbar
Just for fun, I added a bottom bar to show how many wishes are saved:

