SwiftData Predicate not working.

My predicate:

#Predicate<Transaction>{ transaction in transaction.date! >= startDate && transaction.date! <= endDate && transaction.category! == "Income" && transaction.ttype! == "Business" }

is failing with:

The operation couldn’t be completed. (SwiftData.SwiftDataError error 1.)

The release notes for iOS 17 State:

Fixed: #Predicate does not support UUID, Date, and URL properties. (109539652)

Does anyone have any suggestions?

Answered by thibautrichez in 774090022

It's because you force unwrap your properties inside the predicate.

It works fine if you use flatMap to access the unwrapped date value and define your searched strings outside of the predicate scope

let searchCategory = "Income"
let searchType = "Business"

#Predicate<Transaction> {
    $0.date.flatMap { $0 >= startDate && $0 <= endDate } == true &&
    $0.category == searchCategory &&
    $0.ttype == searchType
}
Accepted Answer

It's because you force unwrap your properties inside the predicate.

It works fine if you use flatMap to access the unwrapped date value and define your searched strings outside of the predicate scope

let searchCategory = "Income"
let searchType = "Business"

#Predicate<Transaction> {
    $0.date.flatMap { $0 >= startDate && $0 <= endDate } == true &&
    $0.category == searchCategory &&
    $0.ttype == searchType
}
SwiftData Predicate not working.
 
 
Q