Bird
Raised Fist0
iOS Swiftmobile~20 mins

SwiftData setup (modern persistence) in iOS Swift - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Notes List
A simple notes app screen that saves and loads notes using SwiftData, Apple's modern persistence framework.
Target UI
-------------------------
| Notes List            |
-------------------------
| + Add Note            |
|-----------------------|
| - Note 1              |
| - Note 2              |
| - Note 3              |
-------------------------
Use SwiftData to save and load notes persistently.
Display a list of notes with their text.
Add a button to add a new note with default text.
Notes should be saved automatically and persist after app restart.
Starter Code
iOS Swift
import SwiftUI
import SwiftData

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

struct NotesListView: View {
  @Query var notes: [Note]

  var body: some View {
    NavigationView {
      List {
        // TODO: Show notes here
      }
      .navigationTitle("Notes List")
      .toolbar {
        // TODO: Add button to add note
      }
    }
  }
}

@main
struct NotesApp: App {
  var body: some Scene {
    WindowGroup {
      NotesListView()
        .modelContainer(for: [Note.self])
    }
  }
}
Task 1
Task 2
Solution
iOS Swift
import SwiftUI
import SwiftData

@Model
class Note: Identifiable {
  var id = UUID()
  var text: String
  init(text: String) {
    self.text = text
  }
}

struct NotesListView: View {
  @Query var notes: [Note]
  @Environment(\.modelContext) private var modelContext

  var body: some View {
    NavigationView {
      List {
        ForEach(notes) { note in
          Text(note.text)
        }
      }
      .navigationTitle("Notes List")
      .toolbar {
        Button {
          let newNote = Note(text: "New note")
          modelContext.insert(newNote)
        } label: {
          Image(systemName: "plus")
        }
        .accessibilityLabel("Add Note")
      }
    }
  }
}

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

This app uses SwiftData, Apple's modern persistence framework, to save and load notes automatically.

The @Model attribute defines the Note class as a data model.

The @Query property wrapper fetches all saved notes from the persistent store.

The list displays each note's text.

The '+' button creates a new Note with default text and inserts it into the model context, which saves it automatically.

The .modelContainer(for:) modifier sets up the SwiftData container for persistence.

This setup means notes persist between app launches without extra code.

Final Result
Completed Screen
-------------------------
| Notes List            |
-------------------------
| + Add Note            |
|-----------------------|
| - New note            |
| - Note 1              |
| - Note 2              |
-------------------------
Tapping the '+' button adds a new note with text 'New note' to the list.
Notes remain saved and visible after restarting the app.
Stretch Goal
Add the ability to delete notes by swiping left on a note in the list.
💡 Hint
Use the .onDelete modifier on the List and remove the note from the modelContext.

Practice

(1/5)
1. What is the purpose of marking a class with @Model in SwiftData?
easy
A. It disables saving data for that class.
B. It makes the class visible only to the current view.
C. It tells SwiftData to manage and save instances of that class automatically.
D. It converts the class into a SwiftUI view.

Solution

  1. Step 1: Understand the role of @Model

    The @Model attribute marks a class as a data model for SwiftData to manage persistence.
  2. Step 2: Recognize automatic data management

    SwiftData automatically saves and tracks changes for classes marked with @Model.
  3. Final Answer:

    It tells SwiftData to manage and save instances of that class automatically. -> Option C
  4. Quick Check:

    @Model means automatic data management [OK]
Hint: Remember: @Model means SwiftData saves your data class [OK]
Common Mistakes:
  • Thinking @Model creates a UI component
  • Assuming @Model disables saving
  • Confusing @Model with view modifiers
2. Which of the following is the correct way to set up a SwiftData model container in your app's main entry point?
easy
A. let container = ModelContainer(for: MyModel.self)
B. let container = .modelContainer(for: MyModel.self)
C. let container = ModelContainer(for: [MyModel].self)
D. let container = .modelContainer(for: [MyModel].self)

Solution

  1. Step 1: Recall the correct syntax for model container setup

    SwiftData uses ModelContainer(for: MyModel.self) to create a container for a single model type.
  2. Step 2: Identify the correct option

    let container = ModelContainer(for: MyModel.self) uses the correct constructor syntax.
  3. Final Answer:

    let container = ModelContainer(for: MyModel.self) -> Option A
  4. Quick Check:

    Model container setup uses ModelContainer(for: Type.self) [OK]
Hint: ModelContainer(for: MyModel.self) [OK]
Common Mistakes:
  • Using [MyModel].self array syntax incorrectly
  • Using .modelContainer() which is a view modifier
  • Forgetting .self after the type
3. Given this SwiftUI view using SwiftData:
struct ContentView: View {
  @Environment(\.modelContext) private var context
  @Query var items: [Item]

  var body: some View {
    List(items) { item in
      Text(item.name)
    }
  }
}
What will happen if you add a new Item to context?
medium
A. The new item will be saved but not displayed in the list.
B. The list will not update until the app restarts.
C. The app will crash because @Query cannot detect changes.
D. The list will automatically update to show the new item.

Solution

  1. Step 1: Understand @Query and @Environment(\.modelContext)

    @Query fetches data from the model container and updates the view automatically when data changes.
  2. Step 2: Recognize automatic UI updates

    Adding a new Item to context triggers the @Query to refresh, updating the list.
  3. Final Answer:

    The list will automatically update to show the new item. -> Option D
  4. Quick Check:

    @Query updates UI on data change [OK]
Hint: @Query auto-refreshes UI when data changes [OK]
Common Mistakes:
  • Thinking UI updates only on app restart
  • Believing @Query is static data
  • Assuming app crashes on data change
4. You wrote this code but your app crashes at runtime:
@Model
class Task {
  var title: String
  init(title: String) {
    self.title = title
  }
}
What is the likely cause of the crash?
medium
A. The class is missing a default initializer for SwiftData.
B. You must mark the class as final when using @Model.
C. The property title must be optional.
D. You cannot use classes with @Model, only structs.

Solution

  1. Step 1: Check SwiftData model requirements

    SwiftData requires model classes to have a default initializer or all properties to have default values.
  2. Step 2: Identify missing default initializer

    The class has a custom initializer but no default one, causing runtime issues.
  3. Final Answer:

    The class is missing a default initializer for SwiftData. -> Option A
  4. Quick Check:

    SwiftData models need default initializers [OK]
Hint: Ensure @Model classes have default initializers [OK]
Common Mistakes:
  • Thinking @Model requires final keyword
  • Making properties optional unnecessarily
  • Believing only structs can be @Model
5. You want to create a SwiftData model for a Book with a title and optional author. You also want to fetch all books with a non-empty author in a SwiftUI view. Which code snippet correctly defines the model and query?
hard
A.
@Model
class Book {
  var title: String
  var author: String
  init() { title = ""; author = "" }
}
@Query(filter: #Predicate { $0.author != "" }) var books: [Book]
B.
@Model
class Book {
  var title: String = ""
  var author: String? = nil
}
@Query(filter: #Predicate { $0.author != nil && !$0.author!.isEmpty }) var books: [Book]
C.
@Model
class Book {
  var title: String
  var author: String?
}
@Query(filter: #Predicate { $0.author != nil }) var books: [Book]
D.
@Model
class Book {
  var title: String = ""
  var author: String = ""
}
@Query(filter: #Predicate { $0.author.isEmpty }) var books: [Book]

Solution

  1. Step 1: Define model with optional author and default values

    @Model
    class Book {
      var title: String = ""
      var author: String? = nil
    }
    @Query(filter: #Predicate { $0.author != nil && !$0.author!.isEmpty }) var books: [Book]
    correctly defines author as optional with a default nil and title with a default empty string.
  2. Step 2: Use a filter predicate to fetch books with non-empty author

    The filter checks author != nil and that author is not empty, matching the requirement.
  3. Final Answer:

    Correctly defines the model and query for non-empty authors. -> Option B
  4. Quick Check:

    Optional author + filter for non-empty =
    @Model
    class Book {
      var title: String = ""
      var author: String? = nil
    }
    @Query(filter: #Predicate { $0.author != nil && !$0.author!.isEmpty }) var books: [Book]
    [OK]
Hint: Use optional property and filter for non-empty string [OK]
Common Mistakes:
  • Forgetting to make author optional
  • Using empty string author without optional
  • Incorrect filter logic for non-empty strings
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard