I'm building a SwiftUI app using SwiftData. In my app I have a Customer model with an optional codable structure Contact. Below is a simplified version of my model:
@Model class Customer {
var name: String = ""
var contact: Contact?
init(name: String, contact: Contact? = nil) {
self.name = name
self.contact = contact
}
struct Contact: Codable, Equatable {
var phone: String
var email: String
var allowSMS: Bool
}
}
I'm trying to query all the Customers that have a contact with @Query
. For example:
@Query(filter: #Predicate<Customer> { customer in
customer.contact != nil
}) var customers: [Customer]
However no matter how I set the predicate I always get an error:
BugDemo crashed due to an uncaught exception NSInvalidArgumentException
. Reason: keypath contact not found in entity Customer.
How can I fix this so that I'm able to filter by contact not nil in my Model?