ViewAction(for:)
Provides a view with access to a feature’s ViewAction
s.
@attached(extension, conformances: ViewActionSending) macro ViewAction<R>(for: R.Type) where R : Reducer, R.Action : ViewAction
If you want to restrict what actions can be sent from the view you can use this macro along with the ViewAction
protocol. You start by conforming your reducer’s Action
enum to the ViewAction
protocol, and moving view-specific actions to its own inner enum:
@Reducer
struct Feature {
struct State { /* ... */ }
enum Action: ViewAction {
case loginResponse(Bool)
case view(View)
enum View {
case loginButtonTapped
}
}
// ...
}
Then you can apply the ViewAction(for:)
macro to your view by specifying the type of the reducer that powers the view:
@ViewAction(for: Feature.self)
struct FeatureView: View {
let store: StoreOf<Feature>
// ...
}
The macro does two things:
It adds a
send
method to the view that you can use instead ofstore.send
. This allows you to send view actions more simply, without wrapping the action in.view(…)
:Button("Login") { - store.send(.view(.loginButtonTapped)) + send(.loginButtonTapped) }
It creates warning diagnostics if you try sending actions through
store.send
rather than using thesend
method on the view:Button("Login") { store.send(.view(.loginButtonTapped)) //┬───────── //╰─ ⚠️ Do not use 'store.send' directly when using '@ViewAction' }