SwiftData Predicate Issue

I'm in the process of converting one of my apps to SwiftData. I converted the other ones over. This app has a much more involved Schema, but SwiftData seems to handle it well. My issue is when I try to fetch data based on a. #Predicate. Here's my code.

let predicate = #Predicate<Data> { data in
            data.result == result
            && data.variable!.starts(with: SomeString)
        }
        let sortBy = [SortDescriptor<Data>(\.result]
        let descriptor = FetchDescriptor<Data>(predicate: predicate, sortBy: sortBy)
        
        if let theData = try? context?.fetch(descriptor) {

The if let at the bottom fails. Note that 'variable' is optional while result is not. I have to use ! in the predicate since it's a bool that is returned. If my predicate were just data.result == result, then all is well. I can then check the received data for the second condition in the predicate just fine. It just doesn't work inside of the Predicate. The same is true if I used contains. Anybody else having this issue? I'm using Xcode 15.0 beta 6.

Accepted Answer

I thought I had a fix, but I do not have a fix.

I actually have found a workaround. Here it is.

let predicate = #Predicate<Data> { data in
    data.result == result
    && data.variable?.starts(with: SomeString) ?? false
}

Note the data.variable?. and the ?? false. This works. I still don't think I should have to discover these things. Something needs to be fixed on Apple's end.

Maybe, those codes can help your:

let object = MyObject(name: "name 2") let predicate = #Predicate<MyObject>{ $0.name == "name 2" }

try? modelContext.delete(model: MyObject.self, where: predicate)

SwiftData Predicate Issue
 
 
Q