0
0
iOS Swiftmobile~5 mins

SwiftData setup (modern persistence) in iOS Swift

Choose your learning style9 modes available
Introduction

SwiftData helps your app save and load data easily. It keeps your information safe even when the app closes.

You want to save user notes or settings on the device.
You need to keep a list of favorite items that the user can access later.
Your app should remember user progress or scores between sessions.
You want to store simple data without using complex databases.
Syntax
iOS Swift
import SwiftData

@Model
class Item {
  var name: String
  init(name: String) {
    self.name = name
  }
}

@main
struct MyApp: App {
  var body: some Scene {
    WindowGroup {
      ContentView()
        .modelContainer(for: [Item.self])
    }
  }
}

The @Model attribute marks a class as data you want to save.

The .modelContainer(for:) modifier sets up storage for your data models.

Examples
This defines a simple Task model with a title and a done status.
iOS Swift
import SwiftData

@Model
class Task {
  var title: String
  var done: Bool = false
  init(title: String) {
    self.title = title
  }
}
This sets up the app to use the Task model for data storage.
iOS Swift
import SwiftUI
import SwiftData

@main
struct MyApp: App {
  var body: some Scene {
    WindowGroup {
      TaskListView()
        .modelContainer(for: [Task.self])
    }
  }
}
Sample App

This app lets you add notes and saves them using SwiftData. Notes stay saved even if you close the app.

iOS Swift
import SwiftUI
import SwiftData

@Model
class Note {
  var content: String
  init(content: String) {
    self.content = content
  }
}

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

  var body: some View {
    VStack {
      TextField("Enter note", text: $newNote)
        .textFieldStyle(.roundedBorder)
        .padding()
      Button("Add Note") {
        let note = Note(content: newNote)
        context.insert(note)
        try? context.save()
        newNote = ""
      }
      List(notes, id: \.self) { note in
        Text(note.content)
      }
    }
    .padding()
  }
}

@main
struct NotesApp: App {
  var body: some Scene {
    WindowGroup {
      ContentView()
        .modelContainer(for: [Note.self])
    }
  }
}
OutputSuccess
Important Notes

Always call try? context.save() after inserting or changing data to keep it saved.

Use @Query to automatically get updated data from your storage.

SwiftData works well with SwiftUI and updates your UI when data changes.

Summary

SwiftData makes saving app data easy and safe.

Mark your data classes with @Model and set up storage with .modelContainer(for:).

Use @Environment(\.modelContext) and @Query to work with your saved data in views.