Error querying optional Codable with SwiftData

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?

Use a separate @Model class Contact instead, works well for me. Even though Contact is Codable in your code, SwiftData does not store it like a model class.

You should try something like customer.contact.flatMap { $0 } == false or your previous Boolean, which may work. Unwrapping optionals are done using flat map in Predicate macros.

Error querying optional Codable with SwiftData
 
 
Q