Bird
0
0

Given this SwiftData setup code snippet, what will be the output when fetching all Person objects?

medium📝 Predict Output Q4 of 15
iOS Swift - Local Data Persistence
Given this SwiftData setup code snippet, what will be the output when fetching all Person objects?
let container = ModelContainer(for: Person.self)
let context = container.mainContext
let people = try? context.fetch(FetchDescriptor<Person>())
print(people?.count ?? 0)
ANumber of Person objects stored in the container
BAlways prints 0 because fetchRequest is invalid
CThrows a runtime error due to missing save
DPrints nil because context is not initialized
Step-by-Step Solution
Solution:
  1. Step 1: Understand ModelContainer and FetchDescriptor

    The container is created for Person, context is obtained, and FetchDescriptor<Person>() is called to get all Person objects.
  2. Step 2: Analyze the fetch result

    If there are Person objects saved, the count will be printed. If none, 0 is printed. No runtime error or nil context occurs here.
  3. Final Answer:

    Number of Person objects stored in the container -> Option A
  4. Quick Check:

    Fetching with context returns stored objects count [OK]
Quick Trick: fetchRequest() returns all saved objects count [OK]
Common Mistakes:
  • Assuming fetchRequest is invalid
  • Expecting runtime error without save
  • Thinking context is nil after container creation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes