0
0
iOS Swiftmobile~5 mins

CRUD operations with SwiftData in iOS Swift

Choose your learning style9 modes available
Introduction

CRUD means Create, Read, Update, and Delete data. SwiftData helps you do these actions easily in your iOS apps.

You want to save user notes in your app.
You need to show a list of saved contacts.
You want users to edit their profile information.
You want to remove old or unwanted data from your app.
Syntax
iOS Swift
import SwiftData

// Define a model
@Model
class Item {
  var id: UUID
  var name: String

  init(id: UUID = UUID(), name: String) {
    self.id = id
    self.name = name
  }
}

// Create
let newItem = Item(name: "Example")
modelContext.insert(newItem)

// Read
let items = try modelContext.fetch(Item.self)

// Update
newItem.name = "Updated Name"
try modelContext.save()

// Delete
modelContext.delete(newItem)
try modelContext.save()
@Model marks your data class for SwiftData storage.
Use modelContext to manage data operations like insert, fetch, save, and delete.
Examples
Defines a Task model with an ID, title, and done status.
iOS Swift
@Model
class Task {
  var id: UUID
  var title: String
  var done: Bool

  init(id: UUID = UUID(), title: String, done: Bool = false) {
    self.id = id
    self.title = title
    self.done = done
  }
}
Creates and saves a new Task.
iOS Swift
let task = Task(title: "Buy milk")
modelContext.insert(task)
try modelContext.save()
Fetches all tasks and prints their titles.
iOS Swift
let tasks = try modelContext.fetch(Task.self)
for task in tasks {
  print(task.title)
}
Updates a task's done status and saves the change.
iOS Swift
task.done = true
try modelContext.save()
Sample App

This app lets you add notes, see them in a list, and delete them by swiping. It uses SwiftData to save notes automatically.

iOS Swift
import SwiftUI
import SwiftData

@Model
class Note {
  var id: UUID
  var content: String

  init(id: UUID = UUID(), content: String) {
    self.id = id
    self.content = content
  }
}

struct ContentView: View {
  @Environment(\.modelContext) private var modelContext
  @Query private var notes: [Note]
  @State private var newNote = ""

  var body: some View {
    VStack {
      TextField("New note", text: $newNote)
        .textFieldStyle(.roundedBorder)
        .padding()

      Button("Add Note") {
        let note = Note(content: newNote)
        modelContext.insert(note)
        try? modelContext.save()
        newNote = ""
      }
      .padding()

      List {
        ForEach(notes, id: \.id) { note in
          Text(note.content)
        }
        .onDelete { indexSet in
          for index in indexSet {
            let note = notes[index]
            modelContext.delete(note)
          }
          try? modelContext.save()
        }
      }
    }
    .padding()
  }
}

@main
struct NotesApp: App {
  var body: some Scene {
    WindowGroup {
      ContentView()
        .modelContainer(for: [Note.self])
    }
  }
}
OutputSuccess
Important Notes
Always save changes with try? modelContext.save() after insert, update, or delete.
Use @Query to automatically fetch and update your UI when data changes.
Handle errors in real apps; here we use try? for simplicity.
Summary
CRUD means Create, Read, Update, and Delete data.
SwiftData uses @Model classes and modelContext to manage data.
Use @Query to fetch data and keep your UI updated automatically.