从符合协议的通用交互器传递已发布的变量

pass down a published var from an generic interactor that conforms to protocol

我在很多地方用不同的交互器使用SomeView,所以它使用了一个符合协议InteractorProtocol的通用交互器。问题是 SomeView 有几个 SomeButton 视图,它们将 @Binding 作为参数,我无法将我的 someState1 和 someState2 变量传递给 SomeButton。我可以将我的交互器传递给 SomeButton 并在那里使用交互器变量,但感觉不对。有没有解决的办法?交互器的解决方案可能会有所不同以使其正常工作吗?

protocol InteractorProtocol {
    var someState1: Bool { get set }
    var someState1Published: Published<Bool> { get }
    var someState1Publisher: Published<Bool>.Publisher { get }

    var someState2: Bool { get set }
    var someState2Published: Published<Bool> { get }
    var someState2Publisher: Published<Bool>.Publisher { get }

}

class SomeInteractor: ObservableObject & InteractorProtocol {
    @Published var someState1 = true
    var someState1Published: Published<Bool> { _someState1 }
    var someState1Publisher: Published<Bool>.Publisher { $someState1 }

    @Published var someState2 = true
    var someState2Published: Published<Bool> { _someState2 }
    var someState2Publisher: Published<Bool>.Publisher { $someState2 }

}

struct SomeView<Interactor: InteractorProtocol & ObservableObject>: View {
    @ObservedObject var interactor: Interactor

    var body: some View {
        HStack {
            SomeButton(selected: self.interactor.$someState1) // not allowed
            SomeButton(selected: self.interactor.$someState2) // not allowed
        }
    }
}

struct SomeButton: View {
    @Binding var selected: Bool
    var body: some View {
        Text("text...")
        .background(selected ? Color.green : Color.red)
    }
}

以下应该有效:

protocol InteractorProtocol: ObservableObject {
   var someState1: Bool { get set }
   // ...
}

class SomeInteractor: InteractorProtocol {
   @Published var someState1: Bool = true
   // ...
}

struct SomeView<Interactor: InteractorProtocol>: View {
   @ObservedObject var interactor: Interactor

   var body: some View {
      HStack {
         SomeButton(selected: self.$interactor.someState1)
      }
   }
}