SwiftData. Predicate. Issue accessing self (Entity) inside a Predicate

@Model final class Entry {
    var value: Int
    var date: Date
    var item: Item?
    init(value: Int, date: Date) {
        self.value = value
        self.date = date
    }
}

@Model
final class Item {
    var name: String
    @Relationship(deleteRule:.cascade, inverse: \Entry.item) var entries: [Entry]
    init(name: String) {
        self.name = name
        entries = []
    }
}

extension Item {
    func checkingDate(in context: ModelContext)->Date{
        try! context.fetch(FetchDescriptor<Entry>(predicate:#Predicate<Entry>{$0.item == self})).last!.date
    }
}

same if self == self

Why I'm fetching and not directly accessing entries: https://developer.apple.com/forums/thread/735735

Accepted Answer

Based on my experience, using self inside #predicate is not allowed. Do you have unique identifier field for Item?

If so store that then use unique identifier in a variable and then use id inside your #predicate.

Assume name is the unique identifier then use the following code

example:

let id = self.name
let predicate = #predicate { $0.item.name == id }
....

I feel even #Predicate<Entry>{$0.item == name} should work, give it a try without storing it in a variable.

yes, works

SwiftData. Predicate. Issue accessing self (Entity) inside a Predicate
 
 
Q