How to define a protocol to include a property with @Published property wrapper

后端 未结 6 558
情话喂你
情话喂你 2020-12-15 09:42

When using @Published property wrapper following current SwiftUI syntax, it seems very hard to define a protocol that includes a property with @Published, or I definitely ne

6条回答
  •  悲哀的现实
    2020-12-15 10:21

    Try this

    import Combine
    import SwiftUI
    
    // MARK: - View Model
    
    final class MyViewModel: ObservableObject {
    
        @Published private(set) var value: Int = 0
    
        func increment() {
            value += 1
        }
    }
    
    extension MyViewModel: MyViewViewModel { }
    
    // MARK: - View
    
    protocol MyViewViewModel: ObservableObject {
    
        var value: Int { get }
    
        func increment()
    }
    
    struct MyView: View {
    
        @ObservedObject var viewModel: ViewModel
    
        var body: some View {
    
            VStack {
                Text("\(viewModel.value)")
    
                Button("Increment") {
                    self.viewModel.increment()
                }
            }
        }
    }
    

提交回复
热议问题