### Basic TestStore Initialization Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/README.md Initialize a TestStore with the initial state and reducer for your feature. This is the starting point for most tests. ```swift @Test func basics() async { let store = TestStore(initialState: Feature.State()) { Feature() } } ``` -------------------------------- ### Send Action to Start Timer Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/TestingTCA.md Sends the `.startTimerButtonTapped` action to the `TestStore`. This action triggers the effect that starts the timer. No state change is expected immediately after this action. ```swift await store.send(.startTimerButtonTapped) ``` -------------------------------- ### Define legacy binding state Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/MigrationGuides/MigratingTo1.7.md Reducer setup using BindingState and BindableAction. ```swift @Reducer struct Feature { struct State { @BindingState var text = "" @BindingState var isOn = false } enum Action: BindableAction { case binding(BindingAction) } var body: some ReducerOf { /* ... */ } } ``` -------------------------------- ### Initialize TestStore for Feature Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/TestingTCA.md Sets up a `TestStore` for the `Feature` reducer with an initial state. This is the starting point for testing state mutations and effects. ```swift @MainActor struct TimerTests { @Test func basics() async { let store = TestStore(initialState: Feature.State(count: 0)) { Feature() } } } ``` -------------------------------- ### File Storage Example Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/SharingState.md Demonstrates how to use fileStorage to persist an array of users. Ensure all instances of shared state are updated to avoid runtime issues. ```swift extension URL { static let users = URL(/* ... */) } @Shared(.fileStorage(.users)) var users: [User] = [] ``` -------------------------------- ### Define a feature reducer with stack state Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/MigrationGuides/MigratingTo1.7.md Initial setup for a feature using StackState and StackAction. ```swift @Reducer struct Feature { struct State { var path: StackState = [] } enum Action { case path(StackAction) } var body: some ReducerOf { /* ... */ } } ``` -------------------------------- ### Feature View Controller Setup Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/README.md This snippet shows how to set up a UIKit view controller to interact with a Composable Architecture store. It includes observing state changes and sending actions. ```swift class FeatureViewController: UIViewController { let store: StoreOf init(store: StoreOf) { self.store = store super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() let countLabel = UILabel() let decrementButton = UIButton() let incrementButton = UIButton() let factLabel = UILabel() // Omitted: Add subviews and set up constraints... observe { [weak self] in guard let self else { return } countLabel.text = "\(self.store.count)" factLabel.text = self.store.numberFact } } @objc private func incrementButtonTapped() { self.store.send(.incrementButtonTapped) } @objc private func decrementButtonTapped() { self.store.send(.decrementButtonTapped) } @objc private func factButtonTapped() { self.store.send(.numberFactButtonTapped) } } ``` -------------------------------- ### Executing Shared Logic Before Core Logic Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/Performance.md This example shows how helper methods provide flexibility to execute shared logic before the core logic, unlike the dedicated action approach. ```swift case .buttonTapped: let sharedEffect = self.sharedComputation(state: &state) state.count += 1 return sharedEffect ``` -------------------------------- ### Debugging Action Changes Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/FAQ.md Example output from the _printChanges() reducer operator showing state transitions. ```text received action: AppFeature.Action.syncUpsList(.addSyncUpButtonTapped) AppFeature.State( _path: [:], _syncUpsList: SyncUpsList.State( - _destination: nil, + _destination: .add( + SyncUpForm.State( + … + ) + ), _syncUps: #1 […] ) ) ``` -------------------------------- ### Sharing Logic via Helper Methods (Efficient) Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/Performance.md This example demonstrates the recommended, efficient pattern of sharing logic using helper methods within the reducer. This avoids extra action dispatches and simplifies testing. ```swift @Reducer struct Feature { @ObservableState struct State { /* ... */ } enum Action { /* ... */ } var body: some Reducer { Reduce { state, action in switch action { case .buttonTapped: state.count += 1 return self.sharedComputation(state: &state) case .toggleChanged: state.isEnabled.toggle() return self.sharedComputation(state: &state) case let .textFieldChanged(text): state.description = text return self.sharedComputation(state: &state) } } } func sharedComputation(state: inout State) -> Effect { // Some shared work to compute something. return .run { send in // A shared effect to compute something } } } ``` -------------------------------- ### ViewStore.binding(get:send:) Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Extensions/ViewStoreBinding.md Creates a binding to a specific piece of state using a getter and a way to send actions. ```APIDOC ## binding(get:send:) ### Description Creates a binding to a specific piece of state within the `ViewStore`'s state. This overload requires a `get` function to extract the state and a `send` function to send actions when the binding changes. ### Method `binding` ### Endpoint N/A (This is a method within a Swift library, not a REST API endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift // Example usage within a SwiftUI view struct MyView: View { let store: StoreOf var body: some View { WithViewStore(self.store) { viewStore in TextField( "Enter text", binding: viewStore.binding( get: \.textValue, // Extracts the String value send: { .textChanged($0) } // Sends an action when text changes ) ) } } } ``` ### Response #### Success Response (200) N/A (This method returns a `Binding`) #### Response Example N/A ``` -------------------------------- ### Define Feature Reducer Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/README.md Start by defining the main reducer for your feature. This macro will generate the necessary boilerplate for your reducer. ```swift import ComposableArchitecture @Reducer struct Feature { } ``` -------------------------------- ### Type-Safe In-Memory Key Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/SharingState.md Provides an example of creating a type-safe key for in-memory persistence using SharedReaderKey. ```swift extension SharedReaderKey where Self == InMemoryKey> { static var users: Self { inMemory("users") } } ``` -------------------------------- ### Stack-based Navigation Path Example Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/WhatIsNavigation.md Define a navigation path as an array of states for stack-based navigation. This approach easily handles complex and recursive navigation scenarios, such as navigating through movies and actors, by maintaining a flat array of feature states. ```swift let path: [Path] = [ .movie(/* ... */), .actors(/* ... */), .actor(/* ... */), .movies(/* ... */), .movie(/* ... */), ] ``` -------------------------------- ### Using Dynamic Member Lookup for State Navigation Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Extensions/Reducer.md This example demonstrates using dot-chaining syntax with dynamic member lookup and case paths to access nested state for sheet presentation. ```swift .sheet( item: $store.scope(\.destination?.editForm, action: \.destination.editForm) ) { store in FormView(store: store) } ``` -------------------------------- ### Testing Reducer Logic with Dedicated Actions Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/Performance.md This example shows how testing becomes more complex when using dedicated actions for shared logic, requiring assertions on intermediate shared actions. ```swift let store = TestStore(initialState: Feature.State()) { Feature() } store.send(.buttonTapped) { $0.count = 1 } store.receive(\.sharedComputation) { // Assert on shared logic } store.send(.toggleChanged) { $0.isEnabled = true } store.receive(\.sharedComputation) { // Assert on shared logic } store.send(.textFieldChanged("Hello")) { $0.description = "Hello" } store.receive(\.sharedComputation) { // Assert on shared logic } ``` -------------------------------- ### Sharing Logic via Dedicated Actions (Inefficient) Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/Performance.md This example demonstrates an inefficient pattern of sharing logic by sending a dedicated action for shared computation. This incurs the overhead of multiple action dispatches. ```swift @Reducer struct Feature { @ObservableState struct State { /* ... */ } enum Action { /* ... */ } var body: some Reducer { Reduce { state, action in switch action { case .buttonTapped: state.count += 1 return .send(.sharedComputation) case .toggleChanged: state.isEnabled.toggle() return .send(.sharedComputation) case let .textFieldChanged(text): state.description = text return .send(.sharedComputation) case .sharedComputation: // Some shared work to compute something. return .run { send in // A shared effect to compute something } } } } } ``` -------------------------------- ### Using App Storage for Shared State Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/SharingState.md Demonstrates how to use the @Shared property wrapper with the .appStorage persistence strategy to manage shared state. This setup allows for testing shared state without actual persistence across test runs. ```swift struct State: Equatable { @Shared(.appStorage("count")) var count: Int } ``` -------------------------------- ### Using @Reducer Macro Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Extensions/Reducer.md Annotate your reducer with @Reducer to automate boilerplate code and drop explicit Reducer conformance. This example shows the transformation from a manual conformance to using the macro. ```swift @Reducer struct CounterFeature { @ObservableState struct State { var count = 0 } enum Action { case decrementButtonTapped case incrementButtonTapped } var body: some ReducerOf { Reduce { state, action in switch action { case .decrementButtonTapped: state.count -= 1 return .none case .incrementButtonTapped: state.count += 1 return .none } } } } ``` -------------------------------- ### Using NavigationStack with Path Reducers Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Extensions/Reducer.md This example demonstrates how to use SwiftUI's NavigationStack initializer with a path reducer. It utilizes the `store.case` computed property to switch on the Path.State enum and extract stores for each case. ```swift NavigationStack(path: $store.scope(\.path, action: \.path)) { // Root view } destination: { store in switch store.case { case let .add(store): AddView(store: store) case let .detail(store): DetailView(store: store) case let .edit(store): EditView(store: store) } } ``` -------------------------------- ### Tree-based Navigation State Example Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/WhatIsNavigation.md Use `@Presents` to declare optional state for navigation destinations in tree-based navigation. This statically enforces valid navigation paths, such as navigating to an 'edit' screen only after a 'detail' screen. ```swift @ObservableState struct State { @Presents var editItem: EditItemFeature.State? // ... } ``` -------------------------------- ### Setting Initial Shared State in Tests Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/SharingState.md Shows how to set an initial value for shared state within a test. This is useful for controlling the starting state of shared values during testing. It also includes a workaround for potential conflicts with app entry points. ```swift @Test func basics() { @Shared(.appStorage("count")) var count = 42 // Shared state will be 42 for all features using it. let store = TestStore(…) } ``` -------------------------------- ### WithViewStore Initialization Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Extensions/WithViewStore.md Documentation for initializing a WithViewStore instance. ```APIDOC ## init(_:observe:content:file:line:) ### Description Initializes a WithViewStore to observe state changes and render content. ### Parameters - **store** (Store) - Required - The store to observe. - **observe** (Closure) - Required - A closure to transform the store's state. - **content** (ViewBuilder) - Required - The view content to render based on the observed state. ``` -------------------------------- ### MyApp Entry Point with Composable Architecture Store Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md This Swift code demonstrates how to set up the main application entry point using the Composable Architecture. It initializes the store with initial state and the main reducer. ```swift import ComposableArchitecture @main struct MyApp: App { var body: some Scene { WindowGroup { FeatureView( store: Store(initialState: Feature.State()) { Feature() } ) } } } ``` -------------------------------- ### Counting Elements in NavigationPath Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/StackBasedNavigation.md Shows how to get the number of elements currently in a SwiftUI NavigationPath. ```swift path.count ``` -------------------------------- ### Application Entry Point Without Manual Dependency Construction Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/README.md Demonstrates the simplified application entry point where the main App struct no longer needs to construct dependencies manually. The live dependency is provided automatically. ```swift @main struct MyApp: App { var body: some Scene { WindowGroup { FeatureView( store: Store(initialState: Feature.State()) { Feature() } ) } } } ``` -------------------------------- ### Application Entry Point with Live Dependency Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/README.md Provide the live implementation of the dependency when initializing the application's root view. This uses `URLSession` to fetch data from a real API. ```swift @main struct MyApp: App { var body: some Scene { WindowGroup { FeatureView( store: Store(initialState: Feature.State()) { Feature( numberFact: { number in let (data, _) = try await URLSession.shared.data( from: URL(string: "http://number-trivia.com/\(number)")! ) return String(decoding: data, as: UTF8.self) } ) } ) } } } ``` -------------------------------- ### Define a feature reducer with IdentifiedArray Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/MigrationGuides/MigratingTo1.7.md Example of a reducer structure using IdentifiedArrayOf for row state. ```swift @Reducer struct Feature { @ObservableState struct State { var rows: IdentifiedArrayOf = [] } enum Action { case rows(IdentifiedActionOf) } var body: some ReducerOf { /* ... */ } } ``` -------------------------------- ### Reducer Initialization and Conformance Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Extensions/Reduce.md Methods for initializing reducers and implementing the core reduction logic. ```APIDOC ## Reducer Initialization ### Description Methods to create instances of a Reducer. ### Methods - init(_:)-6xl6k: Initializes a standard reducer. - init(_:)-9kwa6: Initializes a type-erased reducer. ## Reducer Conformance ### Description Methods required to conform to the Reducer protocol. ### Methods - body-20w8t: The body property of the reducer. - reduce(into:action:)-1t2ri: The primary method for handling actions and updating state. ``` -------------------------------- ### Feature Reducer with Optional State Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/MigrationGuides/MigratingTo1.7.md Example reducer structure containing optional child state. ```swift @Reducer struct Feature { @ObservableState struct State { var child: Child.State? } enum Action { case child(Child.Action) } var body: some ReducerOf { /* ... */ } } ``` -------------------------------- ### Initialize a TestStore Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Create a TestStore to track and assert state evolution during tests. ```swift @Test func basics() async { let store = TestStore(initialState: Feature.State()) { Feature() } } ``` -------------------------------- ### View skipped assertion diffs Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/TestingTCA.md Example of the diff output generated when exhaustivity is set to off and assertions are skipped. ```diff AppFeature.State(   authenticatedTab: .loggedOut( Login.State( - isLoading: false + isLoading: true, … ) )   ) ``` ```diff   AppFeature.State( - authenticatedTab: .loggedOut(…) + authenticatedTab: .loggedIn( + Profile.State(…) + ), …   ) ``` -------------------------------- ### Representing non-sensical navigation paths Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/WhatIsNavigation.md Examples of invalid navigation states that can be expressed using stack-based arrays. ```swift let path: [Path] = [ .edit(/* ... */), .detail(/* ... */) ] ``` ```swift let path: [Path] = [ .edit(/* ... */), .edit(/* ... */), .edit(/* ... */), ] ``` -------------------------------- ### WithViewStore Initializers Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Extensions/WithViewStoreInit.md This section covers the different initializers available for the WithViewStore struct, allowing for flexible state observation and view content rendering. ```APIDOC ## WithViewStore Initializers This documentation outlines the various initializers for the `WithViewStore` struct, which is used to provide a `ViewStore` to a view's content closure. ### Overloads These initializers provide different ways to configure the `ViewStore` observation. #### `init(_:observe:removeDuplicates:content:file:line:)` - **Description**: Initializes `WithViewStore` with a store, an observation function, and an optional `removeDuplicates` closure. - **Method**: `init` (Swift initializer) - **Endpoint**: N/A (Swift struct initializer) #### `init(_:observe:send:content:file:line:)` - **Description**: Initializes `WithViewStore` with a store, an observation function, and a `send` function for actions. - **Method**: `init` (Swift initializer) - **Endpoint**: N/A (Swift struct initializer) #### `init(_:observe:send:removeDuplicates:content:file:line:)` - **Description**: Initializes `WithViewStore` with a store, an observation function, a `send` function, and an optional `removeDuplicates` closure. - **Method**: `init` (Swift initializer) - **Endpoint**: N/A (Swift struct initializer) ### Bindings These initializers are specifically designed for use with bindings, allowing for two-way data flow. #### `init(_:observe:content:file:line:)` - **Description**: Initializes `WithViewStore` for use with bindings, observing state and providing it to the content closure. - **Method**: `init` (Swift initializer) - **Endpoint**: N/A (Swift struct initializer) #### `init(_:observe:removeDuplicates:content:file:line:)` - **Description**: Initializes `WithViewStore` for bindings with an optional `removeDuplicates` closure. - **Method**: `init` (Swift initializer) - **Endpoint**: N/A (Swift struct initializer) #### `init(_:observe:send:content:file:line:)` - **Description**: Initializes `WithViewStore` for bindings, observing state and providing a `send` function for actions. - **Method**: `init` (Swift initializer) - **Endpoint**: N/A (Swift struct initializer) #### `init(_:observe:send:removeDuplicates:content:file:line:)` - **Description**: Initializes `WithViewStore` for bindings with a `send` function and an optional `removeDuplicates` closure. - **Method**: `init` (Swift initializer) - **Endpoint**: N/A (Swift struct initializer) ``` -------------------------------- ### Creating a Store Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Extensions/Store.md Initializes a new store with the given state, reducer, and dependencies. ```APIDOC ## init(initialState:reducer:withDependencies:) ### Description Initializes a new store with the given state, reducer, and dependencies. ### Parameters #### Path Parameters - **initialState** (State) - The initial state of the store. - **reducer** (Reducer) - The reducer that will handle actions and state updates. - **withDependencies** (Dependencies) - A closure that provides the dependencies for the store. ### Request Example ```swift let store = Store( initialState: CounterState(), reducer: counterReducer, withDependencies: { // Provide dependencies here } ) ``` ### Response #### Success Response A new `Store` instance. #### Response Example ```swift Store ``` ``` -------------------------------- ### Initialize TestStore for Feature Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/TestingTCA.md Initialize a `TestStore` with the initial state and reducer of a feature. Tests using `TestStore` should be marked `async` and recommended to use `@MainActor`. ```swift import Testing @MainActor struct CounterTests { @Test func basics() async { let store = TestStore(initialState: Feature.State(count: 0)) { Feature() } } } ``` -------------------------------- ### Non-exhaustive integration test flow Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/TestingTCA.md An example of a non-exhaustive test that ignores intermediate state changes by setting exhaustivity to off. ```swift let store = TestStore(initialState: AppFeature.State()) { AppFeature() } store.exhaustivity = .off // ⬅️ await store.send(\.login.submitButtonTapped) await store.receive(\.login.delegate.didLogin) { $0.selectedTab = .activity } ``` -------------------------------- ### Counter with Timer Effects Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Extensions/Reducer.md Extends the counter feature to include timer functionality, handling starting, stopping, and ticking effects. ```swift struct CounterFeature: Reducer { @ObservableState struct State { var count = 0 } enum Action { case decrementButtonTapped case incrementButtonTapped case startTimerButtonTapped case stopTimerButtonTapped case timerTick } enum CancelID { case timer } var body: some ReducerOf { Reduce { state, action in switch action { case .decrementButtonTapped: state.count -= 1 return .none case .incrementButtonTapped: state.count += 1 return .none case .startTimerButtonTapped: return .run { send in while true { try await Task.sleep(for: .seconds(1)) await send(.timerTick) } } .cancellable(CancelID.timer) case .stopTimerButtonTapped: return .cancel(CancelID.timer) case .timerTick: state.count += 1 return .none } } } } ``` -------------------------------- ### Provide Live Dependency in App Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Inject a live implementation of the dependency at the application entry point. ```swift @main struct MyApp: App { var body: some Scene { WindowGroup { FeatureView( store: Store(initialState: Feature.State()) { Feature( numberFact: { number in let (data, _) = try await URLSession.shared.data( from: URL(string: "http://number-trivia.com/\(number)")! ) return String(decoding: data, as: UTF8.self) } ) } ) } } } ``` -------------------------------- ### File-Private Shared State Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/SharingState.md Example of making shared state properties fileprivate to enforce encapsulation and prevent external mutation. ```swift struct State { @Shared(.appStorage("count")) fileprivate var count = 0 } ``` -------------------------------- ### TestStore Initialization Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Extensions/TestStore.md Methods for creating and configuring a TestStore instance to test a specific reducer. ```APIDOC ## init(initialState:reducer:withDependencies:fileID:file:line:column:) ### Description Initializes a new TestStore to test a reducer with a given initial state and optional dependencies. ### Parameters #### Request Body - **initialState** (State) - Required - The starting state for the test. - **reducer** (Reducer) - Required - The reducer logic to be tested. - **withDependencies** (Closure) - Optional - A closure to override dependencies for the test environment. ``` -------------------------------- ### Potential Race Condition Example Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/SharingState.md Illustrates a potential race condition when reading shared state before mutating it, even within `withLock`. ```swift let currentCount = state.count state.$count.withLock { $0 = currentCount + 1 } ``` -------------------------------- ### Configure reducer with key path syntax Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/MigrationGuides/MigratingTo1.4.md Modern reducer configuration using key path syntax for improved type inference and autocomplete. ```swift Reduce { state, action in // ... } .forEach(\.rows, action: \.rows) { RowFeature() } ``` -------------------------------- ### TestStore Initialization for Stack Navigation Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/StackBasedNavigation.md Initializes a TestStore for the parent Feature with a CounterFeature already on the navigation stack. ```swift @Test func dismissal() { let store = TestStore( initialState: Feature.State( path: StackState([ .counter(CounterFeature.State(count: 3)) ]) ) ) { CounterFeature() } ``` -------------------------------- ### Custom Read-Only Persistence Strategy Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/SharingState.md Example of using @SharedReader with a custom persistence strategy like '.remoteConfig' for loading and subscribing to remote data. ```swift @SharedReader(.remoteConfig) var remoteConfig ``` -------------------------------- ### Exhaustive integration test flow Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/TestingTCA.md An example of an exhaustive test requiring assertions on every state change and effect within a nested feature. ```swift let store = TestStore(initialState: AppFeature.State()) { AppFeature() } // 1️⃣ Emulate user tapping on submit button. await store.send(\.login.submitButtonTapped) { // 2️⃣ Assert how all state changes in the login feature $0.login?.isLoading = true // ... } // 3️⃣ Login feature performs API request to login, // and sends response back into system. await store.receive(\.login.loginResponse.success) { // 4️⃣ Assert how all state changes in the login feature $0.login?.isLoading = false // ... } // 5️⃣ Login feature sends a delegate action to let parent // feature know it has successfully logged in. await store.receive(\.login.delegate.didLogin) { // 6️⃣ Assert how all of app state changes due to that action. $0.authenticatedTab = .loggedIn( Profile.State(...) ) // ... // 7️⃣ *Finally* assert that the selected tab switches to activity. $0.selectedTab = .activity } ``` -------------------------------- ### Configuring In-Memory Storage for UI Tests Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/SharingState.md Illustrates how to configure dependencies in an app's entry point to use in-memory storage for .appStorage and .fileStorage during UI testing. This prevents state bleeding between tests by disabling actual persistence. ```swift @main struct EntryPoint: App { let store = Store(initialState: AppFeature.State()) { AppFeature() } withDependencies: { if ProcessInfo.processInfo.environment["UITesting"] == "true" { $0.defaultAppStorage = UserDefaults( suiteName:"\(NSTemporaryDirectory())\(UUID().uuidString)" )! $0.defaultFileStorage = .inMemory } } } ``` -------------------------------- ### Testing with TestStore Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/FAQ.md Demonstrates testing user flows and effect responses using TestStore. ```swift store.send(.refreshButtonTapped) { $0.isLoading = true } store.receive(\.userResponse) { $0.currentUser = User(id: 42, name: "Blob") $0.isLoading = false } ``` -------------------------------- ### Testing Shared State Increment Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/SharingState.md An example test case for the Feature reducer, asserting that tapping the increment button correctly updates the shared count. ```swift @Test func increment() async { let store = TestStore(initialState: Feature.State(count: Shared(0))) { Feature() } await store.send(.incrementButtonTapped) { $0.$count.withLock { $0 = 1 } } } ``` -------------------------------- ### Reducer(state:action:) Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Extensions/ReducerMacro.md Initializes a new Reducer with specific state and action types. ```APIDOC ## Reducer(state:action:) ### Description Initializes a reducer that defines how state changes in response to actions. ### Parameters - **state** (Type) - Required - The state type managed by the reducer. - **action** (Type) - Required - The action type handled by the reducer. ``` -------------------------------- ### View Action Type Constraint Example Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/MigrationGuides/MigratingTo1.7.md Illustrates that a view cannot send actions not defined within its 'View' action enum, preventing type errors. ```swift viewStore.send(.loginResponse(false)) // 🛑 Type 'Feature.Action.View' has no member 'loginResponse' ``` -------------------------------- ### Use ForEach with Store scoping Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/MigrationGuides/MigratingTo1.7.md The modern approach using vanilla ForEach with store scoping. ```swift ForEach( store.scope(state: \.rows, action: \.rows), id: \.state.id ) { childStore in ChildView(store: childStore) } ``` -------------------------------- ### Extending Generated State Type Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/TreeBasedNavigation.md This example demonstrates how to extend the automatically generated state type for a destination enum to conform to protocols like `Equatable` and `Sendable`. ```swift extension InventoryFeature.Destination.State: Equatable, Sendable {} ``` -------------------------------- ### Initializing NavigationStackController for UIKit Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/StackBasedNavigation.md Demonstrates how to initialize a NavigationStackController for use with UIKit, integrating with a Composable Architecture store and defining destination view controllers. ```swift class AppController: NavigationStackController { private var store: StoreOf! convenience init(store: StoreOf) { @UIBindable var store = store self.init(path: $store.scope(\.path, action: \.path)) { RootViewController(store: store) } destination: { store in switch store.case { case .addItem(let store): AddViewController(store: store) case .detailItem(let store): DetailViewController(store: store) case .editItem(let store): EditViewController(store: store) } } self.store = store } } ``` -------------------------------- ### Reducer Implementation Using Dependency Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/README.md Implement the reducer logic to use the injected dependency. This example shows how to call the `numberFact` dependency within a `.run` effect. ```swift case .numberFactButtonTapped: return .run { [count = state.count] send in let fact = try await self.numberFact(count) await send(.numberFactResponse(fact)) } ``` -------------------------------- ### Explicit Destination Reducer Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/MigrationGuides/MigratingTo1.8.md This is the traditional way to define a destination reducer with explicit Scopes for each possible navigation target. It requires more lines of code and manual setup for each case. ```swift @Reducer struct Destination { @ObservableState enum State { case add(FormFeature.State) case detail(DetailFeature.State) case edit(EditFeature.State) } enum Action { case add(FormFeature.Action) case detail(DetailFeature.Action) case edit(EditFeature.Action) } var body: some ReducerOf { Scope(state: \.add, action: \.add) { FormFeature() } Scope(state: \.detail, action: \.detail) { DetailFeature() } Scope(state: \.edit, action: \.edit) { EditFeature() } } } ``` -------------------------------- ### Constructing a Test Store with Dependency Overrides Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/README.md Shows how to construct a TestStore for a feature. Dependencies are automatically provided, but specific dependencies can be overridden for testing purposes using the withDependencies closure. ```swift let store = TestStore(initialState: Feature.State()) { Feature() } withDependencies: { $0.numberFact.fetch = { "\($0) is a good number Brent" } } // ... ``` -------------------------------- ### Deriving Shared State from an IdentifiedArray Element Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/SharingState.md Access a specific element within a shared `IdentifiedArray` using the `[id:]` subscript and a special initializer to get a `Shared`. ```swift @Shared(.fileStorage(.todos)) var todos: IdentifiedArrayOf = [] guard let todo = Shared($todos[id: todoID]) else { return } todo // Shared ``` -------------------------------- ### Testing Binding Actions Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/Bindings.md Demonstrates how to test binding actions by sending a BindingAction that specifies the key path and new value. ```swift /* Rather than send a specific action describing how a binding changed, such as .displayNameChanged("Blob"), you will send a ``BindingAction`` action that describes which key path is being set to what value, such as \.displayName, "Blob": */ ``` -------------------------------- ### Computed Property in State Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/Performance.md Example of defining a computed property in a parent feature's state that derives child state. This can lead to performance issues when used with scoping. ```swift extension ParentFeature.State { var computedChild: ChildFeature.State { ChildFeature.State( // Heavy computation here... ) } } ``` -------------------------------- ### Replacing IfLetStore with if let Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/MigrationGuides/MigratingTo1.7.md Transitioning from IfLetStore to standard Swift if-let syntax for optional state scoping. ```swift IfLetStore(store: store.scope(state: \.child, action: \.child)) { childStore in ChildView(store: childStore) } else: { Text("Nothing to show") } ``` ```swift if let childStore = store.scope(state: \.child, action: \.child) { ChildView(store: childStore) } else { Text("Nothing to show") } ``` -------------------------------- ### Configure reducer with legacy syntax Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/MigrationGuides/MigratingTo1.4.md Legacy reducer configuration using the case path prefix operator. ```swift Reduce { state, action in // ... } .forEach(\.rows, action: /Action.row(id:action:)) { RowFeature() } ``` -------------------------------- ### Assert User Flow Steps Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Use send to simulate user actions and verify state updates. ```swift // Test that tapping on the increment/decrement buttons changes the count await store.send(.incrementButtonTapped) { $0.count = 1 } await store.send(.decrementButtonTapped) { $0.count = 0 } ``` -------------------------------- ### App Entry Point Without Dependency Construction Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md When using @Dependency, the application's entry point no longer needs to construct or pass dependencies. The framework handles providing the correct dependencies for the environment (live, preview, or test). ```swift @main struct MyApp: App { var body: some Scene { WindowGroup { FeatureView( store: Store(initialState: Feature.State()) { Feature() } ) } } } ``` -------------------------------- ### Integrating Child Reducer with `ifLet` Operator Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/TreeBasedNavigation.md This example demonstrates how to use the `.ifLet` operator within the parent reducer's body to integrate the domain of the destination reducer with the parent feature. ```swift @Reducer struct InventoryFeature { // ... var body: some ReducerOf { Reduce { state, action in // ... } .ifLet(\.destination, action: \.destination) } } ``` -------------------------------- ### Using PreviewProvider for Previews Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Extensions/Reducer.md An alternative to #Preview for working with macro-generated types is to use the older, non-macro style PreviewProvider. ```swift struct Feature_Previews: PreviewProvider { static var previews: some View { FeatureView( store: Store( initialState: Feature.State( destination: .edit(EditFeature.State()) ) ) { Feature() } ) } } ``` -------------------------------- ### TestStore Initialization with Mocked Dependency Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/README.md Initialize a TestStore providing a mock implementation for the `numberFact` dependency. This ensures deterministic test results. ```swift @Test func basics() async { let store = TestStore(initialState: Feature.State()) { Feature(numberFact: { "\($0) is a good number Brent" }) } } ``` -------------------------------- ### Use Alternative Delimiters for .appStorage Keys Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/MigrationGuides/MigratingTo1.16.md To leverage key-value observing (KVO) for .appStorage with @Shared and enable animations for UserDefaults changes, use delimiters other than '.' or '@' in your keys. This example uses ':' as a delimiter. ```swift @Shared(.appStorage("co:pointfree:count")) var count = 0 ``` -------------------------------- ### Initialize Persisted Shared State with Autoclosure Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/SharingState.md When using persistence strategies, the `wrappedValue` argument of `Shared.init` is an autoclosure. This example shows how to make the initializer argument an autoclosure as well, ensuring it's only evaluated if needed. ```swift public struct State { @Shared public var count: Int // other fields public init(count: @autoclosure () -> Int, /* other fields */) { self._count = Shared(wrappedValue: count(), .appStorage("count")) // other assignments } } ``` -------------------------------- ### Update Store Scope Syntax Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/MigrationGuides/MigratingTo1.25.md Migrate from non-projected key path syntax to projected key path syntax for store scoping. ```diff -.sheet(item: $store.scope(state: \.destination?.edit, action: \.destination.edit)) +.sheet(item: $store.scope(state: \.$destination, action: \.destination).edit) ``` -------------------------------- ### Receive test store actions with case key paths Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/MigrationGuides/MigratingTo1.9.md Simplifies action assertions by using case key path syntax instead of nested enum cases. ```diff -store.receive(.child(.presented(.response(.success("Hello"))))) +store.receive(\.child.response.success) ``` -------------------------------- ### Asserting on actions with key path syntax Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/MigrationGuides/MigratingTo1.4.md Using key path syntax to describe the nesting of action cases received in a TestStore. ```swift store.receive(\.child.presented.response.success) ``` -------------------------------- ### ViewStore.binding(send:) Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Extensions/ViewStoreBinding.md Creates a binding to a specific piece of state using a key path and a way to send actions. ```APIDOC ## binding(send:) ### Description Creates a binding to a specific piece of state within the `ViewStore`'s state using a key path. This overload requires a `send` function to transform the new value into an action. ### Method `binding` ### Endpoint N/A (This is a method within a Swift library, not a REST API endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift // Example usage within a SwiftUI view struct MyView: View { let store: StoreOf var body: some View { WithViewStore(self.store) { viewStore in TextField( "Enter text", binding: viewStore.binding( keyPath: \.textValue, // Key path to the String value send: { .textChanged($0) } // Sends an action when text changes ) ) } } } ``` ### Response #### Success Response (200) N/A (This method returns a `Binding`) #### Response Example N/A ``` -------------------------------- ### UIKit Integration Overview Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Extensions/UIKit.md Provides an overview of the available tools for integrating Composable Architecture with UIKit components. ```APIDOC ## UIKit Integration Overview ### Description The Composable Architecture provides specific tools to bridge the gap between SwiftUI-focused architecture and UIKit application code. ### Topics - **Subscribing to state changes**: Use `observe(_:)-94oxy` and `ObservationToken` to track state updates. - **Presenting alerts and action sheets**: Use `UIAlertController` extensions. - **Stack-based navigation**: Utilize `NavigationStackController` and `UIPushAction`. - **Combine integration**: Use `Store.ifLet(then:else:)`, `Store.publisher`, and `ViewStore.publisher`. ``` -------------------------------- ### Using Type-Safe Key Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/SharingState.md Shows how to use the custom type-safe key with @Shared for cleaner and safer state management. ```swift @Shared(.users) var users: IdentifiedArrayOf = [] ``` -------------------------------- ### Create a SwiftUI view Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md The view observes a StoreOf to render state and send user actions. ```swift struct FeatureView: View { let store: StoreOf var body: some View { Form { Section { Text("\(store.count)") Button("Decrement") { store.send(.decrementButtonTapped) } Button("Increment") { store.send(.incrementButtonTapped) } } Section { Button("Number fact") { store.send(.numberFactButtonTapped) } } if let fact = store.numberFact { Text(fact) } } } } ``` -------------------------------- ### Use legacy ViewStore bindings Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/MigrationGuides/MigratingTo1.7.md Deriving bindings from a ViewStore in the view layer. ```swift WithViewStore(store, observe: { $0 }) { viewStore in Form { TextField("Text", text: viewStore.$text) Toggle(isOn: viewStore.$isOn) } } ``` -------------------------------- ### Driving Alert Presentation with Store (Old Method) Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/MigrationGuides/MigratingTo1.7.md Previously used method for driving an alert presentation from a Store using the library's specific modifier. ```swift .alert(store: store.scope(state: \.$alert, action: \.alert)) ``` -------------------------------- ### Presentation State and Action Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Extensions/ReducerlIfLetPresentation.md Details on `PresentationState` and `PresentationAction` for managing presentation logic within the Composable Architecture. ```APIDOC ## Presentation State and Action ### Description `PresentationState` and `PresentationAction` are types used to manage the state and actions related to presenting child views or features within the Composable Architecture. `DismissEffect` is a related type for handling dismissal logic. ### Method N/A (These are types, not methods) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Use legacy BindingViewState Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/MigrationGuides/MigratingTo1.7.md Handling view-specific state with BindingViewState and BindingViewStore. ```swift struct ViewState: Equatable { @BindingViewState var text: String @BindingViewState var isOn: Bool init(store: BindingViewStore) { self._text = store.$text self._isOn = store.$isOn } } var body: some View { WithViewStore(store, observe: ViewState.init) { viewStore in Form { TextField("Text", text: viewStore.$text) Toggle(isOn: viewStore.$isOn) } } } ``` -------------------------------- ### Testing Shared State Mutations (Correct Approach) Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/SharingState.md Demonstrates the correct method for testing shared state mutations with the Composable Architecture's TestStore. Assertions for shared state changes must be made in the action that triggers the mutation, not in a subsequent receive. ```swift await store.send(.tap) { // ✅ $0.$bool.withLock { $0 = true } } // ❌ Expected state to change, but no change occurred. await store.receive(.response) // ✅ ``` -------------------------------- ### Perception/Bindable/scope(_:action:) Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Extensions/SwiftUIBindingScopeForEach.md Extends Perception's Bindable protocol with a `scope` method for creating scoped bindings, compatible with Composable Architecture patterns. ```APIDOC ## Perception/Bindable/scope(_:action:) ### Description Extends the `Bindable` protocol from the Perception library with a `scope` method. This method allows for the creation of a new binding that represents a sub-part of the original binding's state, while also providing a way to transform actions sent to the new binding before they are forwarded to the original binding. This is particularly useful for managing state within `ForEach` loops or when integrating with the Composable Architecture. ### Method Signature ```swift func scope(_ _ transform: @escaping (inout State) -> Binding, action: @escaping (Action) -> CoreAction ) -> Binding ``` ### Parameters - **transform**: A closure that receives a mutable reference to the parent state and returns a `Binding` to a specific sub-state. - **action**: A closure that maps actions received by the scoped binding to actions that the parent binding can process. ``` -------------------------------- ### Perception/Bindable/scope(_:action:fileID:line:) Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Extensions/SwiftUIBindingScopeIfLet.md Extends Perception's Bindable protocol to provide scoped bindings, enabling more granular state management. ```APIDOC ## `scope(_:action:fileID:line:)` ### Description Extends Perception's `Bindable` protocol to provide scoped bindings. This method allows you to create a new binding that targets a specific piece of state within a larger structure and transforms actions accordingly. ### Method Signature ```swift func scope( _ path: KeyPath, _ action: @escaping (Action) -> Subject.Action, fileID: StaticString = #fileID, line: UInt = #line) -> Binding ``` ### Parameters - ``path`` (KeyPath): The key path to the nested state you want to bind to. - ``action`` ((Action) -> Subject.Action): A closure that maps actions from the nested scope to the actions of the parent `Bindable`. - ``fileID`` (StaticString): The file identifier for debugging purposes (defaults to `#fileID`). - ``line`` (UInt): The line number for debugging purposes (defaults to `#line`). ### Returns A `Binding` that operates on the specified nested state. ``` -------------------------------- ### Configuring ImmediateClock for Tests Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/TestingTCA.md In tests, provide an `ImmediateClock` to the `TestStore` using `withDependencies`. This makes all time-based operations execute instantly. ```swift let store = TestStore(initialState: Feature.State(count: 0)) { Feature() } withDependencies: { $0.continuousClock = ImmediateClock() } ``` -------------------------------- ### Driving Sheet Presentation with Store (Old Method) Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/MigrationGuides/MigratingTo1.7.md Previously used method for driving a sheet presentation from a Store using the library's specific modifier. ```swift .sheet(store: store.scope(state: \.$child, action: \.child)) { store in ChildView(store: store) } ``` -------------------------------- ### NavigationLink Initializers Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Extensions/NavigationLinkState.md This section details the overloads for the NavigationLink initializer, which allows for programmatic navigation within a SwiftUI view hierarchy. It highlights initializers that accept a state binding for managing navigation and a label closure for defining the link's appearance. ```APIDOC ## NavigationLink Initializers ### Description Provides documentation for the `init(state:label:fileID:filePath:line:column:)` initializer for SwiftUI's `NavigationLink`. ### Overloads - `init(_:state:fileID:line:)-1fmz8` - `init(_:state:fileID:line:)-3xjq3` ``` -------------------------------- ### Presenting a Feature by Populating Destination State Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/TreeBasedNavigation.md This code shows how to present a specific feature by creating an instance of its state and assigning it to the `destination` state variable. ```swift case addButtonTapped: state.destination = .addItem(AddFeature.State()) return .none ``` -------------------------------- ### Wrapping View Body with WithPerceptionTracking Source: https://github.com/pointfreeco/swift-composable-architecture/blob/main/Sources/ComposableArchitecture/Documentation.docc/Articles/SharingState.md Demonstrates the correct way to wrap a view's body with WithPerceptionTracking to ensure proper updates when accessing shared state in pre-observation apps on iOS 16 or earlier. ```swift struct FeatureView: View { let store: StoreOf var body: some View { WithPerceptionTracking { Form { Text(store.sharedCount.description) } } } } ```