I would like to display a list of objects queried from SwiftData, each objects having a Toggle. I obviously need a bool for each object for the state of the toggle. The usual way of doing things is to put a isChecked
member in the Student
object, but I can’t (the actual code is worse as I don’t have only two courses, maths and physics, but a list of courses coming from a query from the database). Of course, a student can appear in many different courses, so I can’t even have one isChecked
in the Student
object that could work for all the courses.
@Model
final class Student {
var name: String = ""
...
}
var body: some View {
List {
Section("Maths") {
ForEach(mathStudents(class: class)) { student in
HStack{
Text(student.name)
Toggle(isOn: ???) {}.onChange(of: ???) { oldValue, newValue in
...some code...
}
}
}
}
Section("Physics") {
ForEach(physicsStudents(class: class)) { student in
HStack{
Text(student.name)
Toggle(isOn: ???) {}.onChange(of: ???) { oldValue, newValue in
...some code...
}
}
}
}
}
}
var mathStudents: [Student] {
...
}
var physicsStudents: [Student] {
...
}
So my question, is : Where can I put my family of bool for the toggles and how can I initialize them ?