ViewStore

A ViewStore is an object that can observe state changes and send actions. They are most commonly used in views, such as SwiftUI views, UIView or UIViewController, but they can be used anywhere it makes sense to observe state or send actions.

ViewStore.swift:94ViewStore.md
iOS
deprecated
macOS
deprecated
tvOS
deprecated
watchOS
deprecated
@dynamicMemberLookup @preconcurrency @MainActor final class ViewStore<ViewState, ViewAction>

In SwiftUI applications, a ViewStore is accessed most commonly using the WithViewStore view. It can be initialized with a store and a closure that is handed a view store and returns a view:

var body: some View {
  WithViewStore(self.store, observe: { $0 }) { viewStore in
    VStack {
      Text("Current count: \(viewStore.count)")
      Button("Increment") { viewStore.send(.incrementButtonTapped) }
    }
  }
}

View stores can also be observed directly by views, scenes, commands, and other contexts that support the @ObservedObject property wrapper:

@ObservedObject var viewStore: ViewStore<State, Action>

In UIKit applications a ViewStore can be created from a Store and then subscribed to for state updates:

let store: Store<State, Action>
let viewStore: ViewStore<State, Action>
private var cancellables: Set<AnyCancellable> = []

init(store: Store<State, Action>) {
  self.store = store
  self.viewStore = ViewStore(store, observe: { $0 })
}

func viewDidLoad() {
  super.viewDidLoad()

  self.viewStore.publisher.count
    .sink { [weak self] in self?.countLabel.text = $0 }
    .store(in: &self.cancellables)
}

@objc func incrementButtonTapped() {
  self.viewStore.send(.incrementButtonTapped)
}

Creating a view store

Accessing state

Sending actions

SwiftUI integration