Published computed properties in SwiftUI model objects

前端 未结 3 1589
南笙
南笙 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:42

    The simplest & fastest is to use value-type model.

    Here is a simple demo. Tested & worked with Xcode 12 / iOS 14

    struct TestTallies: View {
        @StateObject private var group = GroupOfTallies()     // SwiftUI 2.0
    //    @ObservedObject private var group = GroupOfTallies()     // SwiftUI 1.0
    
        var body: some View {
            VStack {
                Text("Cumulative: \(group.cumulativeCount)")
                Divider()
                Button("Add") { group.elements.append(Tallies(count: 1)) }
                Button("Update") { group.elements[0].count = 5 }
            }
        }
    }
    
    struct Tallies: Identifiable {       // << make struct !!
      let id = UUID()
      var count = 0
    }
    
    class GroupOfTallies: Identifiable, ObservableObject {
      let id = UUID()
      @Published var elements: [Tallies] = []
    
        var cumulativeCount: Int {
          return elements.reduce(0) { $0 + $1.count }
        }
    }
    

提交回复
热议问题