I encountered some issues while working with predicates within an initializer and bought "SwiftData by Example" hoping to find a solution. Unfortunately, the book did not address my specific problem, so I'm reaching out for guidance.
I'm working with two models in my application: Project and Panel. Here's a brief overview of their structures:
// Project model
import Foundation
import SwiftData
@Model
public class Project {
var name: String
@Attribute(.unique) var number: String
var customer: String
var details: String
@Relationship(deleteRule: .cascade) var panels = [Panel]()
@Attribute(.externalStorage) var photo: Data?
// Initializer omitted for brevity
}
// Panel model
import Foundation
import SwiftData
@Model
public class Panel {
@Attribute(.unique) var number: String
var name: String
var details: String
weak var project: Project?
@Attribute(.externalStorage) var photo: Data?
// Initializer omitted for brevity
}
The user experience begins with presenting a list of projects. Once a project is selected, the application navigates to a view displaying all panels associated with that project. Here’s the problematic initializer in my Panel view model:
init(searchString: String = "", sortOrder: [SortDescriptor<Panel>] = [], project: Project, path: Binding<NavigationPath>, isEditing: Binding<Bool>) {
let projectNumber = project.number
let predicate = #Predicate<Panel> { panel in
if panel.project?.number == projectNumber {
if searchString.isEmpty {
return true
} else {
return panel.number.localizedStandardContains(searchString)
|| panel.name.localizedStandardContains(searchString)
}
} else {
return false
}
}
_panels = Query(filter: predicate, sort: sortOrder)
self.project = project
_path = path
_isEditing = isEditing
}
I'm having trouble when attempting to filter panels by their associated project using a predicate. If I try to add a predicate to check the optional panel.project == project, I encounter an error.
Could you provide any insights or suggestions on what might be going wrong here?
Thank you for your time and help.