Bird
0
0

Which code snippet correctly defines the model and query?

hard📝 Application Q15 of 15
iOS Swift - Local Data Persistence
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?
A<pre>@Model class Book { var title: String var author: String init() { title = ""; author = "" } }</pre> <pre>@Query(filter: #Predicate { $0.author != "" }) var books: [Book]</pre>
B<pre>@Model class Book { var title: String = "" var author: String? = nil }</pre> <pre>@Query(filter: #Predicate { $0.author != nil && !$0.author!.isEmpty }) var books: [Book]</pre>
C<pre>@Model class Book { var title: String var author: String? }</pre> <pre>@Query(filter: #Predicate { $0.author != nil }) var books: [Book]</pre>
D<pre>@Model class Book { var title: String = "" var author: String = "" }</pre> <pre>@Query(filter: #Predicate { $0.author.isEmpty }) var books: [Book]</pre>
Step-by-Step Solution
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]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes