简体   繁体   中英

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM