Bird
0
0

Examine the following SwiftData model declaration:

medium📝 Debug Q6 of 15
iOS Swift - Local Data Persistence
Examine the following SwiftData model declaration:
@Model class Event {
  var date: Date
  var location: String?
}

What is the issue with this model?
AThe class must inherit from NSObject to be a valid model.
BOptional properties are not allowed in SwiftData models.
CThe model is missing an explicit initializer for its properties.
DThe @Model attribute cannot be applied to classes with more than one property.
Step-by-Step Solution
Solution:
  1. Step 1: Understand SwiftData model requirements

    SwiftData models marked with @Model require all stored properties to be initialized either with default values or via an explicit initializer.
  2. Step 2: Analyze the given code

    The class Event declares two properties: date (non-optional) and location (optional). However, no initializer is provided, and no default values are assigned.
  3. Step 3: Identify the error

    Since date is non-optional and lacks a default value, the compiler expects an initializer to set it. Without it, the model is incomplete and will cause a compile-time error.
  4. Final Answer:

    The model is missing an explicit initializer for its properties. -> Option C
  5. Quick Check:

    Non-optional properties need initialization [OK]
Quick Trick: Non-optional properties require initializers or defaults [OK]
Common Mistakes:
  • Assuming optional properties are disallowed
  • Believing inheritance from NSObject is mandatory
  • Thinking @Model limits number of properties

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes