I have two related data models in SwiftData: Group and Task.
On the Task model, Group is optional so I want a list where all the tasks without a group are in a section and then a section with each group and the tasks associated with it.
I've got the second part with the groups/tasks figured out but every way I've tried to get the tasks without a group doesn't work.
Here is the latest iteration that seems like the closest:
MODELS
@Model
class Group: Identifiable {
var id = UUID()
var name: String
var status: String
@Relationship() var tasks = [Task]()
init(name: String, status: String, tasks: [Task] = [Task]()) {
self.name = name
self.status = status
self.tasks = tasks
}
}
@Model
class Task: Identifiable {
var id = UUID()
var name: String
var notes: String = ""
var status: String
@Relationship(inverse: \Group.tasks) var group: Group?
init(name: String, notes: String = "", status: String, group: Group? = nil) {
self.name = name
self.notes = notes
self.status = status
self.group = group
}
}
VIEW
ForEach(tasks){ task in
if task.group.isEmpty == true {
Text("I am a test")
}
}
That works fine if I use task.notes.isEmpty
but as soon as I try to use the related field I get these errors:
Cannot convert value of type '[Task]' to expected argument type 'Binding<C>'
Generic parameter 'C' could not be inferred
I also tried using a query to get the tasks but even though I know I have some tasks without a group association, I don't get any results so clearly my query is flawed somehow.
@Query(filter: #Predicate<Task> { task in
task.group?.name == ""
}) var freeTasks: [Task]
ForEach(freeTasks){ task in
Text(task.name)
}
Any suggestions? I don't care how I go about it, as long as it works :)