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:
Step 1: Define model with optional author and default values
@Model
class Book {
var title: String = ""
var author: String? = nil
}