In my model data class I have a task array.
class Model: ObservableObject {
@Published var tasks: [Task] = Task.sampleData
}
In my HomeView I display these tasks however the user has the ability to use a picker to sort them by the date they were created or by the date they are due. In the HomeView I have an enum that contains the options that the user can sort them by and a state instance to hold the picked value. By default it is set to sort by due date.
@EnvironmentObject private var model: Model
@State private var sortOption: SortOption = .dueDate
enum SortOption {
case dueDate, creationDate
}
I decided to then create a computed value that contains the sorted array so I don't change the original tasks array as it is used to display tasks in other parts of the app.
var sortedTasks: [Task] {
model.tasks.sorted(by: {
if sortOption == .dueDate {
return $0.dueDate < $1.dueDate
} else {
return $0.creationDate < $1.creationDate
}
})
}
And soon after I ran into the problem. My Task Row requires a binding task and I am unable to retrieve the required binding from the computed property which was the sortedTasks array.
// ERROR: Cannot find '$sortedTasks' in scope
ForEach($sortedTasks) { $task in
TaskRow(task: $task)
}
My understanding is that if I want to keep the sortedTasks array then I will have to remove the binding property from the TaskRow but if I want to keep the binding property what should the approach be to display a sorted array without manipulating the tasks array in the data model class? Could the computed property return a sorted array of binding task objects?