binding(get:send:)

Derives a binding from the store that prevents direct writes to state and instead sends actions to the store.

ViewStore.swift:494
iOS
deprecated
macOS
deprecated
tvOS
deprecated
watchOS
deprecated
@MainActor func binding<Value>(get: @escaping (_ state: ViewState) -> Value, send action: ViewAction) -> Binding<Value>

Parameters

get

A function to get the state for the binding from the view store’s full state.

action

The action to send when the binding is written to.

Returns

A binding.

The method is useful for dealing with SwiftUI components that work with two-way Bindings since the Store does not allow directly writing its state; it only allows reading state and sending actions.

For example, an alert binding can be dealt with like this:

struct State { var alert: String? }
enum Action { case alertDismissed }

.alert(
  item: viewStore.binding(
    get: { $0.alert },
    send: .alertDismissed
  )
) { alert in Alert(title: Text(alert.message)) }