ios – Why does passing the view model as a generic work with protocol but having type inference doesn’t for ObservedObject in SwiftUI


So I have a view model that conforms to a protocol in SwiftUI and I don’t understand why the following won’t work but the other option does.

protocol SummaryViewModelProtocol: ObservableObject {
    var textValueString: String { get set }
}

class SummaryViewModel: SummaryViewModelProtocol {
    private var cancellables: Set<AnyCancellable> = []
    @Published private var textValuePublisher: String = ""
    var textValueString: String = ""

    init() {
      setupSubscribers()
    }
}

struct ContentView: View {
    @ObservedObject var viewModel: SummaryViewModelProtocol = SummaryViewModel()

    var body: some View {
        VStack {
            Text(viewModel.textValueSring)
        }
        .padding()
        .onAppear {
            viewModel.loadData()
        }
    }
}

when I have it this I get the error message saying Type ‘any SummaryViewModelProtocol‘ cannot conform to ‘ObservableObject

but if my view uses generics then I don’t have the following error?

struct ContentViewNoError<Model>: View where Model: SummaryViewModelProtocol {
    @ObservedObject var viewModel: Model

    init(viewModel: Model) {
        self.viewModel = viewModel
    }

    var body: some View {
        Text(viewModel.textValueString)
    }
}

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img