Bird
Raised Fist0
iOS Swiftmobile~20 mins

CRUD operations with SwiftData in iOS Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
SwiftData CRUD Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate
2:00remaining
What happens when you save a new SwiftData entity?

You create a new entity instance and call modelContext.insert(newEntity) followed by try? modelContext.save(). What is the expected behavior?

iOS Swift
@Model
class Task {
  var title: String
  init(title: String) {
    self.title = title
  }
}

let newTask = Task(title: "Buy milk")
modelContext.insert(newTask)
try? modelContext.save()
AThe new task is only saved in memory and lost when the app restarts.
BThe new task is saved persistently and will appear in future fetches.
CThe code throws a runtime error because insert is not allowed before save.
DThe new task is saved but only if you call a special commit method afterwards.
Attempts:
2 left
💡 Hint

Think about what modelContext.save() does in SwiftData.

📝 Syntax
intermediate
2:00remaining
Which code correctly updates a SwiftData entity's attribute?

You have a fetched Task entity and want to update its title. Which option is correct?

iOS Swift
func updateTaskTitle(task: Task, newTitle: String) {
  // update code here
  try? modelContext.save()
}
Atask.title = newTitle
Btask.setValue(newTitle, forKey: "title")
CmodelContext.update(task, with: ["title": newTitle])
Dtask.updateTitle(newTitle)
Attempts:
2 left
💡 Hint

SwiftData entities use property wrappers for attributes.

❓ lifecycle
advanced
2:00remaining
What happens if you delete an entity but forget to save the context?

You call modelContext.delete(entity) but do not call modelContext.save(). What is the result?

AThe entity remains in persistent storage until <code>save()</code> is called.
BThe app crashes with an error about unsaved changes.
CThe entity is deleted from memory and persistent storage automatically.
DThe entity is removed immediately from persistent storage.
Attempts:
2 left
💡 Hint

Think about when changes are committed to disk in SwiftData.

❓ navigation
advanced
2:00remaining
How to refresh a SwiftUI list after SwiftData changes?

You display a list of Task entities fetched from SwiftData. After adding a new task, the list does not update automatically. What should you do?

AWrap the list in a <code>NavigationView</code> to enable automatic refresh.
BManually reload the view by calling <code>setNeedsDisplay()</code> on the list.
CUse <code>@Query</code> property wrapper to fetch tasks so the list updates automatically.
DCall <code>modelContext.refreshAll()</code> after saving the new task.
Attempts:
2 left
💡 Hint

SwiftUI and SwiftData integration uses property wrappers for reactive updates.

🔧 Debug
expert
3:00remaining
Why does this SwiftData save fail with a validation error?

Given this entity definition and save code, why does saving fail?

@Model
class User {
  @Attribute(.unique) var email: String
  init(email: String) {
    self.email = email
  }
}

let user1 = User(email: "a@example.com")
let user2 = User(email: "a@example.com")
modelContext.insert(user1)
modelContext.insert(user2)
try modelContext.save()
ABecause <code>modelContext.save()</code> requires a completion handler.
BBecause you must call <code>modelContext.insert()</code> only once per context.
CBecause the email property must be optional to allow duplicates.
DBecause two entities have the same unique email, violating the uniqueness constraint.
Attempts:
2 left
💡 Hint

Look at the attribute modifiers and what they enforce.

Practice

(1/5)
1. What does the @Model attribute in SwiftData represent?
easy
A. A UI component for displaying lists
B. A data model class used to define entities for CRUD operations
C. A function to fetch data from the network
D. A SwiftUI view modifier for styling

Solution

  1. Step 1: Understand the role of @Model

    The @Model attribute marks a class as a data model entity for SwiftData, enabling CRUD operations.
  2. Step 2: Differentiate from UI and functions

    It is not related to UI components, network functions, or view modifiers.
  3. Final Answer:

    A data model class used to define entities for CRUD operations -> Option B
  4. Quick Check:

    @Model defines data entities = B [OK]
Hint: Remember @Model marks data classes, not UI or functions [OK]
Common Mistakes:
  • Confusing @Model with UI components
  • Thinking @Model fetches data
  • Mixing @Model with view modifiers
2. Which of the following is the correct way to declare a SwiftData model class named Book with a title property of type String?
easy
A. @Model class Book { var title: String }
B. @Model struct Book { var title: String }
C. struct Book { var title: String }
D. class Book: ObservableObject { var title: String }

Solution

  1. Step 1: Identify correct @Model usage

    SwiftData requires @Model on a class, not a struct, to define a data entity.
  2. Step 2: Check class vs struct and attribute

    @Model class Book { var title: String } correctly uses @Model with a class and a property.
  3. Final Answer:

    @Model class Book { var title: String } -> Option A
  4. Quick Check:

    @Model + class + properties = D [OK]
Hint: Use @Model with class, not struct, for SwiftData models [OK]
Common Mistakes:
  • Using struct instead of class for @Model
  • Omitting @Model attribute
  • Using ObservableObject instead of @Model
3. Given the following SwiftData code snippet, what will be the output when printing books.count after adding a new book?
struct ContentView: View {
  @Environment(\"modelContext\") private var modelContext
  @Query var books: [Book]

  var body: some View {
    Button(\"Add Book\") {
      let newBook = Book(title: \"SwiftData Basics\")
      modelContext.insert(newBook)
    }
    Text(\"Books count: \(books.count)\")
  }
}
medium
A. Books count: 0
B. Books count: 2
C. Books count: 1
D. Compilation error

Solution

  1. Step 1: Understand @Query and modelContext.insert

    The @Query property fetches all Book entities. Inserting a new Book updates the data source.
  2. Step 2: Check the effect of insertion on books.count

    After inserting one new Book, the count increases by 1, so it will be 1.
  3. Final Answer:

    Books count: 1 -> Option C
  4. Quick Check:

    Insert one book, count updates to 1 [OK]
Hint: Inserting updates @Query results immediately [OK]
Common Mistakes:
  • Assuming count stays 0 after insert
  • Expecting count to be 2 without adding twice
  • Thinking code causes compile error
4. Identify the error in this SwiftData update code snippet:
func updateBookTitle(book: Book, newTitle: String) {
  book.title = newTitle
  modelContext.save()
}
medium
A. No error; code updates title correctly
B. Missing call to modelContext.insert(book)
C. book.title cannot be changed directly; must create new Book
D. modelContext.save() is not a valid method in SwiftData

Solution

  1. Step 1: Check SwiftData update pattern

    In SwiftData, changes to model object properties are tracked automatically, but modelContext.save() is not a valid method to persist changes explicitly.
  2. Step 2: Identify if there's an error

    Directly mutating book.title is correct, but calling modelContext.save() causes an error because the method does not exist.
  3. Final Answer:

    modelContext.save() is not a valid method in SwiftData -> Option D
  4. Quick Check:

    Property change tracked automatically; no save() method = A [OK]
Hint: SwiftData tracks changes automatically; no save() method needed [OK]
Common Mistakes:
  • Thinking modelContext.save() exists
  • Believing properties are immutable
  • Confusing update with insert
5. You want to delete all Book objects with an empty title using SwiftData. Which code snippet correctly performs this operation?
hard
A. books.filter { $0.title.isEmpty }.forEach { modelContext.delete($0) }
B. for book in books where book.title.isEmpty { modelContext.delete(book) }
C. modelContext.deleteAll(Book.self, where: \"title == ''\")
D. modelContext.remove(books.filter { $0.title.isEmpty })

Solution

  1. Step 1: Understand deletion in SwiftData

    To delete objects, you call modelContext.delete(object) for each object.
  2. Step 2: Check each option for correctness

    books.filter { $0.title.isEmpty }.forEach { modelContext.delete($0) } filters books with empty titles and deletes each correctly. for book in books where book.title.isEmpty { modelContext.delete(book) } syntax is invalid in Swift. modelContext.deleteAll(Book.self, where: \"title == ''\") uses a non-existent method. modelContext.remove(books.filter { $0.title.isEmpty }) uses wrong method name.
  3. Final Answer:

    books.filter { $0.title.isEmpty }.forEach { modelContext.delete($0) } -> Option A
  4. Quick Check:

    Filter then delete each = A [OK]
Hint: Filter then delete each object individually [OK]
Common Mistakes:
  • Using invalid for-in with where clause
  • Calling non-existent deleteAll method
  • Using wrong method name like remove
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