Reputation: 1
With SwiftData's @Query
macro, I get an array of model items. Then, I use a computed property to group the items. The computed property is used twice in my view and is therefore also computed twice. If the array is long and the operation is complex, the computed property takes a long time to be computed. How can I change my code to only compute the property once and then whenever data from @Query
changes?
struct GroupListView: View {
@Query var persons: [Person]
var grouped: [[Person]] {
// expensive operation
}
var body: some View {
VStack {
Text("There are \(grouped.count) groups")
List {
ForEach(grouped) { group in
Text("Number of members: \(group.count)")
}
}
}
}
}
I tried to store grouped
as a local variable in GroupListView
instead of using a computed property. The problem with this approach is that I need to declare the variable in the initializer and the view does not update when persons
changes.
I also tried to store grouped
as a local variable in body
but this causes a recomputation whenever any state inside the view changes and not only when persons
changes.
Upvotes: 0
Views: 122