Suppose I have a data model in my SwiftUI app that looks like the following:
class Tallies: Identifiable, ObservableObject {
let id = UUID()
@Published var count = 0
}
class GroupOfTallies: Identifiable, ObservableObject {
let id = UUID()
@Published var elements: [Tallies] = []
}
I want to add a computed property to GroupOfTallies
that resembles the following:
// Returns the sum of counts of all elements in the group
var cumulativeCount: Int {
return elements.reduce(0) { $0 + $1.count }
}
However, I want SwiftUI to update views when the cumulativeCount
changes. This would occur either when elements
changes (the array gains or loses elements) or when the count
field of any contained Tallies
object changes.
I have looked into representing this as an AnyPublisher
, but I don't think I have a good enough grasp on Combine to make it work properly. This was mentioned in this answer, but the AnyPublisher created from it is based on a published Double
rather than a published Array
. If I try to use the same approach without modification, cumulativeCount
only updates when the elements array changes, but not when the count
property of one of the elements changes.