How to use BindingState through protocol? #2104
Answered
by
stephencelis
kakhaberikiknadze
asked this question in
Q&A
-
Assuming I've got module A and module B ExampleModule Apublic protocol MyState: Equatable {
var isOn: BindingState<Bool> { get } // I can't use property wrapper here like @BindingState var isOn: Bool { get }
}
public protocol MyAction: BindableAction {
}
public protocol MyReducer: ReducerProtocol where State: MyState, Action: MyAction {}
public struct MyView<ViewState: MyState, Action: MyAction>: View {
@ObservedObject private var viewStore: ViewStore<ViewState, Action>
init(store: Store<ViewState, Action> {
viewStore = .init(store, observe: { $0 }
}
public var body: some View {
Toggle(isOn: viewStore.binding(\.$isOn) { // This method is unavailable. How to unlock this binding method while using protocol?
Text("Foo")
}
}
} Module Bstruct ConcreteReducer: MyReducer {
struct State: MyState {
@BindingState var isOn: Bool // Compiler would still complain and ask to add var isOn: BindingState<Bool> instead to conform MyReducer.
}
enum Action: MyAction {
case binding(BindingAction<State>)
}
var body: some ReducerProtocol<State, Action> {
Reduce { state, action in
// ..
}
BindingReducer()
}
} |
Beta Was this translation helpful? Give feedback.
Answered by
stephencelis
May 13, 2023
Replies: 1 comment 1 reply
-
Property wrappers' inability to fulfill protocol requirements is a known limitation in Swift. I tried to dig up an issue, but couldn't find one unfortunately. You may have better luck tracking it down than I've had, or you may want to file an issue. If you really need a protocol here, you can adopt non-property wrapper usage: var isOn: BindingState<Bool> { get }
…
-Toggle(isOn: viewStore.binding(\.$isOn)) {
+Toggle(isOn: viewStore.binding(\.isOn)) { // no need for `$` |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
kakhaberikiknadze
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Property wrappers' inability to fulfill protocol requirements is a known limitation in Swift. I tried to dig up an issue, but couldn't find one unfortunately. You may have better luck tracking it down than I've had, or you may want to file an issue.
If you really need a protocol here, you can adopt non-property wrapper usage: