swiftswiftuiprotocolscombineswinject

How to use Swinject to register protocol conforming to ObservableObject?


Right now, I've been running into an issue of registering protocol conforming to ObservableObject. Since ObservableObject uses an associated type, I cannot find a way to register it without compiling error.

This is my simple model, called A

protocol A: ObservableObject {}

This is my simple class, called B

final class B: A {}

Here is my Assembly

final class ViewStoreAssembly: Assembly{
    func assemble(container: Container) {
        container.register(A.self) { _ in
            B()
        }
    }
}

I'm trying to register A comforming to ObservableObject, but the compilation error shows that

Protocol 'A' can only be used as a generic constraint because it has Self or associated type requirements

Does anyone know how to tackle the issue? The benefits of doing this will be

  1. In SwiftUI, we can decouple view out of ViewStore/presenter so that view can be separated from viewModel holder
  2. ViewStore/Presenter can be tested easily by mocking a view

Solution

  • It is better to use instead the following combination (anyway ObservableObject has sense only for classes, and it brings nothing for model protocol itself, and it is not possible to have observer, like ObservedObject, around protocol)

    protocol A {}
    
    final class B: ObservableObject, A {}
    

    I assume the following topics can be helpful as well:

    How to define a protocol as a type for a @ObservedObject property?

    How to create Generic if @EnvironmentObject?