9.7 C
New York
Tuesday, March 25, 2025

ios – SwiftUI MVVM: Single View, 2 completely different ViewModels that conform to ObservableObject


I am offering a particularly simplified instance as an example my level:

  • A single SwiftUI View displaying the identical properties of a ViewModel
  • 2 ViewModels that are ObservableObject subclasses
  • The ViewModels have precisely the identical properties, simply the title/subtitle which are completely different and the underlying methodology calls which are completely different

The right way to appropriately initialize a View in order that it could “personal” the ViewModel?
Usually I am going about this as follows:


struct OverrideView: View {
    @Atmosphere(.dismiss) non-public var dismiss
    @StateObject non-public var viewModel: OverrideViewModelProtocol
    
    init(_ viewModel: @escaping @autoclosure () -> OverrideViewModelProtocol) {
        self._viewModel = StateObject(wrappedValue: viewModel())
    }
    
    var physique: some View {
    }
}

Nonetheless, clearly this does not work since I can not initialize a non-concrete class, the init is anticipating some kind of some OverrideViewModelProtocol:

protocol OverrideViewModelProtocol: ObservableObject {
    var mainTitle: String { get }
    var overrideSelectedSegmentIndex: Int { get set }

    var overrideCommentHeader: String { get }
    var overrideComment: String { get set }
    var overrideSubmitButtonEnabled: Bool { get }
    var overrideShouldDismiss: Bool { get }
    func submitButtonPressed()
}

Clearly, I can not impose that the OverrideViewModelProtocol can also be an ObservableObject, due to this fact I am getting a difficulty:

Kind ‘any OverrideViewModelProtocol’ can not conform to
‘ObservableObject’

One technique to clear up the issue is to create an summary base class and use it as a substitute of the protocol. However is there a means to make use of simply the protocol and prohibit solely ObservableObject subclass to have the ability to conform to it, in order that the View would know that it is a concrete ObservableObject subclass on initialization?

Use-case:
2 barely completely different views, which differ solely in textual content / button titles, in order that I might use 2 completely different view fashions as a substitute of if/else statements contained in the views.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles