Published computed properties in SwiftUI model objects

前端 未结 3 1578
南笙
南笙 2021-01-07 03:38

Suppose I have a data model in my SwiftUI app that looks like the following:

class Tallies: Identifiable, ObservableObject {
  let id = UUID()
  @Published va         


        
3条回答
  •  孤城傲影
    2021-01-07 03:48

    This is similar to the last option of @New Devs answer, but a little shorter, essentially just passing the objectWillChange notification to the parent object:

    import Combine
    
    class Tallies: Identifiable, ObservableObject {
      let id = UUID()
      @Published var count = 0
    
      func increase() {
        count += 1
      }
    }
    
    class GroupOfTallies: Identifiable, ObservableObject {
      let id = UUID()
      var sinks: [AnyCancellable] = []
      
      @Published var elements: [Tallies] = [] {
        didSet {
          sinks = elements.map {
            $0.objectWillChange.sink( receiveValue: objectWillChange.send)
          }
        }
      }
    
      var cumulativeCount: Int {
        return elements.reduce(0) { $0 + $1.count }
      }
    }
    

    SwiftUI Demo:

    struct ContentView: View {
      @ObservedObject
      var group: GroupOfTallies
    
      init() {
        let group = GroupOfTallies()
        group.elements.append(contentsOf: [Tallies(), Tallies()])
        self.group = group
      }
    
      var body: some View {
        VStack(spacing: 50) {
          Text( "\(group.cumulativeCount)")
          Button( action: group.elements.first!.increase) {
            Text( "Increase first")
          }
          Button( action: group.elements.last!.increase) {
            Text( "Increase last")
          }
        }
      }
    }
    

提交回复
热议问题