### Swift: Basic Test Setup for Feature Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Sets up a 'TestStore' for the 'Feature' reducer, initializing its 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() } } } ``` -------------------------------- ### Usage Example: Providing Documentation URL to AI Assistant Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/README.md This example demonstrates how to use the consolidated documentation by providing its raw GitHub URL to an AI coding assistant. This allows the AI to access and understand the Point-Free library documentation effectively. ```text https://raw.githubusercontent.com/juavazmor/pointfree-docs-consolidated/main/swift-composable-architecture-docs.md ``` -------------------------------- ### Implement AudioPlayer Protocols Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-dependencies-docs.md Provides example implementations of the AudioPlayer protocol: a live version interacting with AVFoundation, a mock version for simulation, and an unimplemented version for error reporting. ```swift struct LiveAudioPlayer: AudioPlayer { let audioEngine: AVAudioEngine // ... } struct MockAudioPlayer: AudioPlayer { // ... } struct UnimplementedAudioPlayer: AudioPlayer { func loop(url: URL) async throws { reportIssue("AudioPlayer.loop is unimplemented") } // ... } ``` -------------------------------- ### Migration Guides Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-case-paths-docs.md Documentation on how to migrate existing CasePaths code to newer versions, including the @CasePathable macro. ```APIDOC ## Migration guides # Migration guides Learn how to upgrade your application to the newest version of Case Paths. ## Overview Case Paths is under constant development, and we are always looking for ways to simplify the library, and make it more powerful. As such, we often need to deprecate certain APIs in favor of newer ones. We recommend people update their code as quickly as possible to the newest APIs, and these guides contain tips to do so. > Important: Before following any particular migration guide be sure you have followed all the > preceding migration guides. ## Topics - ``` -------------------------------- ### Stack-based Navigation: Path Example (Swift) Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Illustrates a stack-based navigation path using an array of feature states in Swift. This example shows how to represent a sequence of navigation events, including potential recursive navigation, as a flat array. ```swift enum Path { case movie(MovieFeature.State) case actors(ActorsFeature.State) case actor(ActorFeature.State) case movies(MoviesFeature.State) // ... other cases } let path: [Path] = [ .movie(/* movie state */), .actors(/* actors state */), .actor(/* actor state */), .movies(/* movies state */), .movie(/* movie state */), ] ``` -------------------------------- ### Migrating to 1.1 Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-case-paths-docs.md Guide on migrating existing case path code to utilize the new @CasePathable macro and CaseKeys. ```APIDOC ## MigratingTo1.1 # Migrating to 1.1 Learn how to migrate existing case path code to utilize the new `@CasePathable` macro and ``CaseKeyPath``s. ``` -------------------------------- ### Migration Guide to Case Paths 1.1 in Swift Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-case-paths-docs.md Provides guidance on migrating existing case path code to utilize the `@CasePathable` macro and `CaseKeyPath`s introduced in version 1.1 of the Case Paths library. ```swift # Migrating to 1.1 Learn how to migrate existing case path code to utilize the new `@CasePathable` macro and ``CaseKeyPath``s. ``` -------------------------------- ### Swift: Alert Actions Closure Example Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-navigation-docs.md An example of using a result builder within the `actions` closure of `AlertState` to conditionally present buttons based on application state, such as whether an item is locked. ```swift } actions: { if item.isLocked { ButtonState(role: .destructive, action: .confirmDelete) { TextState("Unlock and delete") } } else { ButtonState(role: .destructive, action: .confirmDelete) { TextState("Delete") } } ButtonState(role: .cancel) { TextState("Nevermind") } } ``` -------------------------------- ### Swift TestStore Initialization Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Initializes a TestStore for the 'Feature' reducer with a specific initial state for the nested counter. This setup is used to begin testing feature interactions. ```swift @Test func dismissal() { let store = TestStore( initialState: Feature.State( counter: CounterFeature.State(count: 3) ) ) { CounterFeature() } } ``` -------------------------------- ### Stack-based Navigation Path Example (Swift) Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Demonstrates a non-sensical navigation path using a stack-based approach, where an edit screen is followed by a detail screen. This highlights a drawback of stack-based navigation in enforcing logical navigation flows. ```swift let path: [Path] = [ .edit(/* ... */), .detail(/* ... */) ] ``` ```swift let path: [Path] = [ .edit(/* ... */), .edit(/* ... */), .edit(/* ... */), ] ``` -------------------------------- ### ViewStore Binding Creation Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Details how to create bindings for a ViewStore, with different overloads for specifying how to get and send values. This is crucial for two-way data flow in SwiftUI. ```swift ComposableArchitecture/ViewStore/binding(get:send:) Overloads - ``binding(get:send:)-l66r`` - ``binding(send:)-7nwak`` - ``binding(send:)-705m7`` ``` -------------------------------- ### Handle Out-of-Life Effects with Unstructured Tasks Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Provides a code example showing how to ensure analytics or persistence effects proceed without cancellation by performing them in an unstructured task when a store deallocates. ```swift return .run { _ in Task { await analytics.track(/* ... */) } } ``` -------------------------------- ### Pushing Detail Feature with NavigationLink Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Demonstrates pushing a 'Detail' feature onto the navigation stack using SwiftUI's NavigationLink. This requires specifying the full state of the feature, starting from the root Path reducer. ```swift Form { NavigationLink( state: RootFeature.Path.State.detail(DetailFeature.State()) ) { Text("Detail") } } ``` -------------------------------- ### Initializing TestStore for Feature Testing in Swift Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Shows the recommended way to initialize a TestStore with initial state and a reducer to test feature logic. Includes necessary imports and actor isolation recommendations. ```swift import Testing @MainActor struct CounterTests { @Test func basics() async { let store = TestStore(initialState: Feature.State(count: 0)) { Feature() } } } ``` -------------------------------- ### Optional State Example in Swift Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Demonstrates an initial approach to managing navigation states using multiple optional properties within a struct. This method can lead to invalid states where multiple options are active simultaneously, causing issues with SwiftUI's presentation capabilities. ```swift @ObservableState struct State { @Presents var detailItem: DetailFeature.State? @Presents var editItem: EditFeature.State? @Presents var addItem: AddFeature.State? // ... } ``` -------------------------------- ### Swift App Entry Point with Composable Architecture Store Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Illustrates the main application structure using SwiftUI and the Composable Architecture. It shows how to construct a store with initial state and a reducer, and then pass it to the main view. Requires the Composable Architecture library. ```swift import ComposableArchitecture @main struct MyApp: App { var body: some Scene { WindowGroup { FeatureView( store: Store(initialState: Feature.State()) { Feature() } ) } } } ``` -------------------------------- ### Set up Base Suite for Isolated Swift Test Dependencies Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-dependencies-docs.md Provides a pattern for creating a base suite in Swift that isolates dependencies for all nested tests. Uses the `.dependencies` trait to ensure each test gets a fresh set of dependencies, preventing state bleed-over. ```swift @Suite(.dependencies) struct BaseSuite {} extension BaseSuite { @Suite struct FeatureTests { @Test func basics() { // ... } } } ``` -------------------------------- ### Exhaustive Testing Example in Composable Architecture Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/composable-architecture-docs.md Demonstrates an exhaustive test flow in the Composable Architecture, showing detailed assertions on state changes and effect handling for a login feature integration. This style requires deep knowledge of the feature's internal workings. ```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 } ``` -------------------------------- ### Swift App Entry Point with Composable Architecture Store Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/composable-architecture-docs.md The main `App` struct that sets up the initial state and reducer for the Composable Architecture. It creates a `Store` and passes it to the `FeatureView`. Requires the `ComposableArchitecture` import. ```swift import ComposableArchitecture @main struct MyApp: App { var body: some Scene { WindowGroup { FeatureView( store: Store(initialState: Feature.State()) { Feature() } ) } } } ``` -------------------------------- ### Swift: Custom Read-Only Persistence Strategy Example Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Shows an example of creating a custom persistence strategy, '.remoteConfig', that only supports loading and subscribing to shared state, making it read-only. This is achieved by conforming to the 'SharedReaderKey' protocol instead of the full 'SharedKey' protocol. ```swift @SharedReader(.remoteConfig) var remoteConfig ``` -------------------------------- ### WithViewStore Initialization for View Creation Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/composable-architecture-docs.md Provides initializers for WithViewStore, a helper for creating views that have access to a ViewStore. It includes parameters for observing state, providing content, and debugging information. ```swift init(_:observe:content:file:line:) init(_:observe:removeDuplicates:content:file:line:) init(_:observe:send:content:file:line:) init(_:observe:send:removeDuplicates:content:file:line:) ``` -------------------------------- ### WithViewStore Initialization Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Explains the various initializers for WithViewStore, which is used to provide a ViewStore to a SwiftUI view hierarchy. It covers different ways to observe state and send actions. ```swift ComposableArchitecture/WithViewStore Creating a view - ``init(_:observe:content:file:line:)-8g15l`` Debugging view updates - ``_printChanges(_:)`` ``` ```swift ComposableArchitecture/WithViewStore/init(_:observe:content:file:line:)-8g15l Overloads - ``WithViewStore/init(_:observe:removeDuplicates:content:file:line:)-7y5bp`` - ``WithViewStore/init(_:observe:send:content:file:line:)-5d0z5`` - ``WithViewStore/init(_:observe:send:removeDuplicates:content:file:line:)-dheh`` Bindings - ``WithViewStore/init(_:observe:content:file:line:)-4gpoj`` - ``WithViewStore/init(_:observe:removeDuplicates:content:file:line:)-1zbzi`` - ``WithViewStore/init(_:observe:send:content:file:line:)-3r7aq`` - ``WithViewStore/init(_:observe:send:removeDuplicates:content:file:line:)-4izbr`` ``` -------------------------------- ### Dependency: Getting the value Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-dependencies-docs.md This section explains how to access the value managed by a `Dependency`. It focuses on the `wrappedValue` property, which provides the concrete implementation of the dependency. ```swift var wrappedValue: Success ``` -------------------------------- ### ViewStore Initialization for SwiftUI Integration Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/composable-architecture-docs.md Demonstrates various initializers for creating a ViewStore, essential for integrating with SwiftUI views. These initializers handle state observation, action sending, and duplicate removal for efficient updates. ```swift init(_:observe:send:removeDuplicates:) init(_:observe:removeDuplicates:) init(_:observe:send:) init(_:observe:) init(_:observe:send:removeDuplicates:) init(_:observe:removeDuplicates:) init(_:observe:send:) init(_:observe:) ``` -------------------------------- ### Simplify Sending Test Store Actions (Swift) Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Illustrates the simplified syntax for sending actions to a TestStore using case key paths, reducing boilerplate and improving readability in integration tests. ```swift store.send(\.path[id: 0].destination.record.startButtonTapped) store.receive(\.path[id: 0].destination.record.timerTick) ``` -------------------------------- ### Providing Live API Dependency in Swift Application Entry Point Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Shows how to instantiate the Feature with a live dependency that interacts with a real API server in the application's 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://numbersapi.com/(number)")! ) return String(decoding: data, as: UTF8.self) } ) } ) } } } ``` -------------------------------- ### Create and Use TestStore for Basic Assertions (Swift) Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/composable-architecture-docs.md Demonstrates creating a TestStore with initial state and a feature reducer, and then sending actions to assert state changes like incrementing a count. ```Swift @Test func basics() async { let store = TestStore(initialState: Feature.State()) { Feature() } } // 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 } ``` -------------------------------- ### Automatic Fulfillment of Reducer Requirements Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/composable-architecture-docs.md An example of a minimal reducer struct that compiles due to the @Reducer macro automatically fulfilling protocol requirements like State, Action, and body. ```swift @Reducer struct Feature {} ``` -------------------------------- ### UUID Generation with Dependency (Swift) Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/composable-architecture-docs.md Example of a domain model using a controllable dependency to generate a UUID. This pattern can cause issues in non-exhaustive test stores when skipped assertions are shown. ```swift struct Model: Equatable { let id: UUID init() { @Dependency(\.uuid) var uuid self.id = uuid() } } ``` -------------------------------- ### Simplifying Test Store Actions with Case Key Paths (Swift) Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/composable-architecture-docs.md Demonstrates the evolution of simplifying test store actions in the Composable Architecture. It shows the transition from verbose action sending to a concise syntax using case key paths for nested actions, improving readability and reducing boilerplate in integration tests. ```swift store.receive(\.child.response.success) ``` ```swift store.receive(\.child.presented.success, "Hello") ``` ```swift store.send(\.path[id: 0].destination.record.startButtonTapped) store.receive(\.path[id: 0].destination.record.timerTick) ``` ```swift -store.send(.destination(.presented(.tap))) +store.send(\.destination.tap) ``` ```swift -store.send(.path(.element(id: 0, action: .tap))) +store.send(\.path[id: 0].tap) ``` ```swift -store.send(.binding(.set(\.firstName, "Blob"))) +store.send(\.binding.firstName, "Blob") ``` ```swift -store.send( - .path( - .element( - id: 0, - action: .destination( - .presented( - .sheet( - .binding( - .set(\.password, "blobisawesome") - ) - ) - ) - ) - ) - ) -) +store.send(\.path[id: 0].destination.sheet.binding.password, "blobisawesome") ``` -------------------------------- ### Using the @Reducer macro (Swift) Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Demonstrates using the @Reducer macro to simplify Reducer protocol conformance in Swift. This example shows how to annotate a struct with @Reducer and remove explicit conformance. ```diff +@Reducer -struct CounterFeature: 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 } } } } ``` -------------------------------- ### Basic TestStore Initialization in Swift Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Initializes a TestStore for testing a specific feature. The store is configured with the initial state and the feature's reducer. This is the foundational step for writing tests. ```swift @Test func basics() async { let store = TestStore(initialState: Feature.State()) { Feature() } } ``` -------------------------------- ### ComposableArchitecture TestStore Initialization and Configuration Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Details the creation and configuration of `TestStore` for testing reducers in The Composable Architecture, including dependency injection and exhaustivity settings. ```swift ComposableArchitecture.TestStore.init(initialState:reducer:withDependencies:fileID:file:line:column:) ComposableArchitecture.TestStoreOf ComposableArchitecture.TestStore.dependencies ComposableArchitecture.TestStore.exhaustivity ComposableArchitecture.TestStore.timeout ComposableArchitecture.TestStore.useMainSerialExecutor ``` -------------------------------- ### Scope Binding for NavigationStack Path Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Provides an example of how to create the necessary scoped binding for the 'path' state and action within the root feature's state and action, to be used with the NavigationStack initializer. ```swift struct RootView: View { @Bindable var store: StoreOf var body: some View { NavigationStack( path: $store.scope(state: \.path, action: \.path) ) { // Root view of the navigation stack } destination: { store in // A view for each case of the Path.State enum } } } ``` -------------------------------- ### AudioPlayer DependencyKey Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-dependencies-docs.md Demonstrates how to define a DependencyKey for the AudioPlayer protocol, specifying live, preview, and test values for dependency injection. ```swift private enum AudioPlayerKey: DependencyKey { static let liveValue: any AudioPlayer = LiveAudioPlayer() static let previewValue: any AudioPlayer = MockAudioPlayer() static let testValue: any AudioPlayer = UnimplementedAudioPlayer() } ``` -------------------------------- ### ComposableArchitecture TestStore Initialization Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/composable-architecture-docs.md Initializes a TestStore with initial state, a reducer, and dependencies, enabling comprehensive testing of TCA reducers. ```swift public init( initialState: State, reducer: Reducer, withDependencies dependencies: (_ environment: inout Environment) -> Void = { _ in }) where State : Sendable, Action : Sendable { // ... implementation details ... } } ``` -------------------------------- ### Using Key Paths for Navigation with State Enum Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/composable-architecture-docs.md Shows an example of using key path syntax with a State enum that has @dynamicMemberLookup and @CasePathable applied. This facilitates optional navigation to a sub-state, like 'editForm'. ```swift .sheet( item: $store.scope(state: \.destination?.editForm, action: \.destination.editForm) ) { FormView(store: store) } ``` -------------------------------- ### DependencyKey: Registering a dependency Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-dependencies-docs.md This documentation details how to register dependencies using the `DependencyKey` protocol. It outlines the properties required for defining the dependency's value, live implementation, test implementation, and preview implementation. ```swift typealias Value var liveValue: Value var testValue: Value var previewValue: Value ``` -------------------------------- ### Presenting a Feature with Enum State in Swift Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Provides an example of how to present a specific feature by updating the optional destination state with a corresponding enum case. This is the standard way to trigger navigation to a child feature. ```swift case addButtonTapped: state.destination = .addItem(AddFeature.State()) return .none ``` -------------------------------- ### Create Live, Mock, and Unimplemented AudioPlayerClient Values Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-dependencies-docs.md Provides static factory methods on `AudioPlayerClient` to create live, mock, and unimplemented instances. The 'unimplemented' version uses a reporting function to indicate uncalled methods during testing. ```swift extension AudioPlayerClient { static var live: Self { let audioEngine: AVAudioEngine return Self(/*...*/) } static let mock = Self(/* ... */) static let unimplemented = Self( loop: { _ in reportIssue("AudioPlayerClient.loop is unimplemented") }, // ... ) } ``` -------------------------------- ### Infinite Loop Warning in Shared State Observation Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Highlights a potential pitfall when observing shared state where a change to the state triggers an update, leading to an infinite loop. This example shows a scenario to avoid. ```swift case .onAppear: return .publisher { state.$count.publisher .map(Action.countUpdated) } case .countUpdated(let count): state.count = count + 1 return .none ``` -------------------------------- ### Observe Shared State Changes with Publisher Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Demonstrates how to observe changes to shared state using the publisher property exposed by the @Shared property wrapper. Includes an example of mapping publisher events to actions. ```swift case .onAppear: return .publisher { state.$count.publisher .map(Action.countUpdated) } case .countUpdated(let count): // Do something with count return .none ``` -------------------------------- ### Defining and Registering a Mock Dependency Client (Swift) Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/composable-architecture-docs.md Shows how to create a type for a dependency (NumberFactClient), conform it to DependencyKey for live implementation, and register it with the application's dependency management system. ```Swift struct NumberFactClient { var fetch: (Int) async throws -> String } extension NumberFactClient: DependencyKey { static let liveValue = Self( fetch: { number in let (data, _) = try await URLSession.shared .data(from: URL(string: "http://numbersapi.com/(number)")! ) return String(decoding: data, as: UTF8.self) } ) } extension DependencyValues { var numberFact: NumberFactClient { get { self[NumberFactClient.self] } set { self[NumberFactClient.self] = newValue } } } ``` -------------------------------- ### Testing with ImmediateClock Dependency Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Shows how to configure a `TestStore` with an `ImmediateClock` to make time-based operations execute instantly during tests. ```swift let store = TestStore(initialState: Feature.State(count: 0)) { Feature() } withDependencies: { $0.continuousClock = ImmediateClock() } ``` -------------------------------- ### Implement Custom Get-Set Subscript for Binding Logic in Swift Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Provides an example of creating a custom subscript on `StoreOf` to encapsulate complex binding logic, such as checking for feature flag existence and toggling it. ```swift // Before // In the view: ForEach(Flag.allCases) { flag in Toggle( flag.description, isOn: viewStore.binding( get: { $0.featureFlags.contains(flag) }, send: { .flagToggled(flag, isOn: $0) } ) ) } // After // In the file: extension StoreOf { subscript(hasFeatureFlag flag: Flag) -> Bool { get { featureFlags.contains(flag) } set { send(.flagToggled(flag, isOn: newValue)) } } } // In the view: ForEach(Flag.allCases) { flag in Toggle( flag.description, isOn: $store[hasFeatureFlag: flag] ) } ``` -------------------------------- ### DependencyValues: Default contexts Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-dependencies-docs.md This documentation describes the default contexts available for `DependencyValues`, namely `live`, `preview`, and `test`. These contexts allow for easy switching between different dependency implementations based on the environment. ```swift live preview test ``` -------------------------------- ### Swift: Using appStorage for Shared State Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Demonstrates how to define a struct with shared state using the appStorage persistence strategy. This setup allows for testing without actual data persistence across runs. ```swift struct State: Equatable { @Shared(.appStorage("count")) var count: Int } ``` -------------------------------- ### Send Actions to Store Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/composable-architecture-docs.md Demonstrates sending actions to a TestStore with initial state and updating specific properties like displayName and protectMyPosts. ```swift let store = TestStore(initialState: Settings.State()) { Settings() } store.send(.binding.displayName, "Blob") { $0.displayName = "Blob" } store.send(.binding.protectMyPosts, true) { $0.protectMyPosts = true ) ``` -------------------------------- ### TCA Action Ping-Ponging Example (Before Optimization) Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Demonstrates the 'ping-ponging' of actions in TCA when multiple effects require sequential execution with intermediate state mutations. This pattern involves sending separate actions for each asynchronous operation. ```swift case .refreshButtonTapped: return .run { send in await send(.userResponse(apiClient.fetchCurrentUser())) } case let .userResponse(response): return .run { send in await send(.moviesResponse(apiClient.fetchMovies(userID: response.id))) } case let .moviesResponse(response): // Do something with response ``` -------------------------------- ### SwiftUI NavigationStack and NavigationLink Initialization Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Demonstrates how to initialize SwiftUI's NavigationStack and NavigationLink with state and actions, integrating with The Composable Architecture for navigation management. ```swift SwiftUI.NavigationStack.init(path:root:destination:fileID:filePath:line:column:) SwiftUI.NavigationLink.init(state:label:fileID:filePath:line:column:) ``` -------------------------------- ### Simplify TestDependencyKey conformance with @DependencyClient Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-dependencies-docs.md This Swift code snippet shows how to simplify the `testValue` conformance for `AudioPlayerClient` by utilizing the `@DependencyClient` macro. The macro automatically generates the necessary unimplemented clients, reducing manual implementation. ```swift extension AudioPlayerClient: TestDependencyKey { static let testValue = Self() } ``` -------------------------------- ### Swift: Model for Alert State Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-navigation-docs.md Defines the structure for an alert within a feature model, including an optional AlertState and an enum for alert actions. This setup allows for managing alert presentation and user interactions. ```swift @Observable class FeatureModel { var alert: AlertState? enum AlertAction { case confirmDelete } // ... } ``` -------------------------------- ### New Store Scoping with Key Paths (Swift) Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Illustrates the recommended approach for scoping stores using key paths for both state and action. This API offers better performance and stable identity. ```swift // ✅ New API ChildView( store: store.scope( state: \.child, action: \.child ) ) ``` -------------------------------- ### Swift: Asserting on received actions (pre-1.6) Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/composable-architecture-docs.md Provides an example of how actions were asserted in `TestStore` prior to version 1.6, focusing on receiving actions without asserting on their payloads. Version 1.6 introduced the capability to assert on payloads. ```swift await store.receive(.child(.delegate(.response(true)))) ``` -------------------------------- ### Dependency: Using a dependency Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-dependencies-docs.md This documentation covers the usage of the `Dependency` type within the project. It details the initializers available for creating and managing dependencies, specifying `fileID`, `filePath`, `line`, and `column` for precise tracking. ```swift init(_:fileID:filePath:line:column:) init(_:fileID:filePath:line:column:) ``` -------------------------------- ### API Client Preview Value Implementation Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-dependencies-docs.md Provides a mock implementation for an API client's fetchUsers and fetchUser endpoints for use in Xcode previews. This allows for synchronous data return without external network calls. It must be defined in the same module as the TestDependencyKey conformance. ```swift extension APIClient: TestDependencyKey { static let previewValue = Self( fetchUsers: { [ User(id: 1, name: "Blob"), User(id: 2, name: "Blob Jr."), User(id: 3, name: "Blob Sr."), ] }, fetchUser: { id in User(id: id, name: "Blob, id: \(id)") } ) } ``` -------------------------------- ### Swift Non-Exhaustive Test Example Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Demonstrates non-exhaustive testing by disabling 'store.exhaustivity' and only asserting the high-level outcome of sending two increment actions, followed by receiving the dismiss action. This approach is more resilient to minor state changes. ```swift @Test func dismissal() { let store = TestStore( initialState: Feature.State( counter: CounterFeature.State(count: 3) ) ) { CounterFeature() } store.exhaustivity = .off await store.send(\.counter.incrementButtonTapped) await store.send(\.counter.incrementButtonTapped) await store.receive(\.counter.dismiss) } ``` -------------------------------- ### Prevent App Execution During Tests (UIApplicationDelegate) Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-dependencies-docs.md Demonstrates how to prevent the main application code from running during tests in an `UIApplicationDelegate`-based entry point. It uses the `isTesting` flag from the `IssueReporting` library to conditionally execute the application's setup logic. ```swift import UIKit import IssueReporting class AppDelegate: NSObject, UIApplicationDelegate { func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { guard !isTesting else { return true } // ... your application setup code ... return true } } ``` -------------------------------- ### Store Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/composable-architecture-docs.md Documentation for the `Store` type, covering creation, state access, action sending, and scoping. ```APIDOC ## Store # ``ComposableArchitecture/Store`` ## Topics ### Creating a store - `init(initialState:reducer:withDependencies:)` - `StoreOf` ### Accessing state - `state-1qxwl` - `subscript(dynamicMember:)-655ef` - `withState(_:) ### Sending actions - `send(_:) - `send(_:animation:) - `send(_:transaction:) - `StoreTask ### Scoping stores - `scope(state:action:)-90255` - `scope(state:action:fileID:filePath:line:column:)-3yvuf` - `scope(state:action:fileID:filePath:line:column:)-2ym6k` - `case` ### Scoping store bindings - `SwiftUI/Binding` ### Combine integration - `StorePublisher` ### Deprecated interfaces - `StoreDeprecations` ``` -------------------------------- ### Swift: Counter Feature with Timer Effects Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/composable-architecture-docs.md Extends the counter feature to include timer functionality. It defines actions for starting, stopping, and handling timer ticks. Effects are used to run a timer asynchronously and send `.timerTick` actions, and to cancel the timer. ```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 } } } } ``` -------------------------------- ### SwiftUI View Structure Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-dependencies-docs.md Demonstrates the basic structure of a SwiftUI View, which conforms to the `View` protocol and exposes a `body` property. This `body` property is the single entry point for constructing the view hierarchy. ```swift struct FeatureView: View { var body: some View { // All of the view is constructed in here... } } ``` -------------------------------- ### Swift: Overriding Shared State in Tests Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/composable-architecture-docs.md Illustrates how to set an initial value for shared state within a test function. This approach ensures the shared state starts with a predictable value, avoiding potential conflicts with app entry point initializations. ```swift @Test func basics() { @Shared(.appStorage("count")) var count = 42 // Shared state will be 42 for all features using it. let store = TestStore(…) } ``` ```swift @Test func basics() { @Shared(.appStorage("count")) var count = 42 count = 42 // NB: Set again to override any value set by the app target. // Shared state will be 42 for all features using it. let store = TestStore(…) } ``` -------------------------------- ### ViewStore Initialization and State Access Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Details the various initializers for ViewStore and how to access its state, including dynamic member subscripting. Covers different ways to observe and remove duplicate state updates. ```swift ComposableArchitecture/ViewStore Creating a view store - ``init(_:observe:send:removeDuplicates:)-9mg12`` - ``init(_:observe:removeDuplicates:)-4f9j5`` - ``init(_:observe:send:)-1m32f`` - ``init(_:observe:)-3ak1y`` - ``ViewStoreOf`` Accessing state - ``state-swift.property`` - ``subscript(dynamicMember:)-kwxk`` Sending actions - ``send(_:)`` - ``send(_:while:)`` - ``yield(while:)`` ``` -------------------------------- ### Non-Exhaustive Integration Test Example in Swift Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Illustrates a non-exhaustive test in TCA by disabling the `exhaustivity` setting. This focuses only on the high-level outcome (tab switching) without asserting internal state changes of the login feature, making tests more resilient to internal refactors. ```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 } ``` -------------------------------- ### Collapsing PresentationAction (Swift) Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Demonstrates a specialized syntax for collapsing the `presented` case of `PresentationAction` when sending actions to a store. ```swift store.send(\.destination.tap) ``` -------------------------------- ### Exhaustive Integration Test Example in Swift Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Demonstrates a detailed, exhaustive test for a login flow in TCA, showing assertions on state changes and effect handling. This approach requires deep knowledge of the feature's internal workings and can lead to brittle tests. ```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 = Profile.State(...) // ... // 7️⃣ *Finally* assert that the selected tab switches to activity. $0.selectedTab = .activity } ``` -------------------------------- ### Simulating User Actions and Asserting State Changes in Swift Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Demonstrates how to send actions to the TestStore and assert that the state changes as expected. This covers simulating button taps and verifying the resulting 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 } ``` -------------------------------- ### DependencyKey Registration Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-dependencies-docs.md Information on registering dependencies using DependencyKey, including defining live, test, and preview values. ```APIDOC # ``Dependencies/DependencyKey`` ## Topics ### Registering a dependency - ``Value`` - ``liveValue`` - ``testValue-535kh`` - ``previewValue-36s5j`` ### Modularizing a dependency - ``TestDependencyKey`` ``` -------------------------------- ### Example of Potential Race Condition with Shared State (Swift) Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Illustrates a potentially problematic way to mutate shared state by reading the value outside of a lock and then attempting to update it within a lock. This highlights the importance of wrapping the entire operation within `withLock`. ```swift let currentCount = state.count state.$count.withLock { $0 = currentCount + 1 } ``` -------------------------------- ### SwiftUI: Previewing FeatureView with an Immediate Clock Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-dependencies-docs.md Demonstrates how to set up an Xcode preview for 'FeatureView'. It uses 'prepareDependencies' to override the 'continuousClock' dependency with an 'ImmediateClock', causing the message to appear instantly. ```swift import SwiftUI import Dependencies #Preview { let _ = prepareDependencies { $0.continuousClock = ImmediateClock() } FeatureView(model: FeatureModel()) } ``` -------------------------------- ### Swift: Automatically fulfill Reducer requirements with @Reducer macro Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Demonstrates how the `@Reducer` macro in the Composable Architecture can automatically generate empty State, Action, and body properties for a reducer. This simplifies the initial setup of features, allowing them to be integrated before their logic is fully implemented. ```swift @Reducer struct Feature { } ``` -------------------------------- ### Replace IfLetStore with Swift's 'if let' Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/composable-architecture-docs.md Demonstrates replacing the IfLetStore helper with standard Swift 'if let' syntax for handling optional states. This improves code clarity and leverages modern observation tools. ```swift @Reducer struct Feature { @ObservableState struct State { var child: Child.State? } enum Action { case child(Child.Action) } var body: some ReducerOf { /* ... */ } } // Previously: // IfLetStore(store: store.scope(state: \.child, action: \.child)) { childStore in // ChildView(store: childStore) // } else: { // Text("Nothing to show") // } // Now: if let childStore = store.scope(state: \.child, action: \.child) { ChildView(store: childStore) } else { Text("Nothing to show") } ``` -------------------------------- ### Sending Actions and Asserting State Changes with TestStore in Swift Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/composable-architecture-docs.md Illustrates the `send` method of TestStore for dispatching actions and asserting state mutations. It highlights the trailing closure used to specify expected state changes, providing clear examples of correct and incorrect mutations. ```swift await store.send(.incrementButtonTapped) { // ... } ``` ```swift await store.send(.incrementButtonTapped) { $0.count = 1 } ``` ```swift await store.send(.incrementButtonTapped) { $0.count = 999 } ``` -------------------------------- ### Override Dependencies for Swift Xcode Previews Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-dependencies-docs.md Demonstrates how to use `prepareDependencies` to override the continuous clock to an `ImmediateClock` specifically for Xcode Previews, ensuring time-based UI updates are instant. ```swift #Preview {\n let _ = prepareDependencies { $0.continuousClock = ImmediateClock() }\n // All access of '@Dependency(\.continuousClock)' in this preview will\n // use an immediate clock.\n FeatureView(model: FeatureModel())\n} ``` -------------------------------- ### Swift: Handling CPU-Intensive Calculations with Effects and Task.yield() Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Provides a Swift code example for managing CPU-intensive computations. It shows how to delegate heavy work to an Effect, run it on a cooperative thread pool, and use `Task.yield()` to prevent blocking, delivering results via actions. ```swift case .buttonTapped: var result = // ... for value in someLargeCollection { // Some intense computation with value } state.result = result ``` ```swift case .buttonTapped: return .run { send in var result = // ... for (index, value) in someLargeCollection.enumerated() { // Some intense computation with value // Yield every once in awhile to cooperate in the thread pool. if index.isMultiple(of: 1_000) { await Task.yield() } } await send(.computationResponse(result)) } case let .computationResponse(result): state.result = result ``` -------------------------------- ### Integrating Live Dependency in Application Entry Point (Swift) Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/composable-architecture-docs.md Demonstrates how to provide a live, network-dependent implementation of a feature's dependency (numberFact) in the main application's 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://numbersapi.com/\(number)")! ) return String(decoding: data, as: UTF8.self) } ) } ) } } } ``` -------------------------------- ### Asserting Specific Child Action in Navigation Stack Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md This example demonstrates how to assert that a specific child action is received within the navigation stack. It constructs a case key path by subscripting `\.path` with an element ID to target a particular child feature's action, such as a `.response` action. ```swift await store.receive(\.path[id: 0].counter.response) { // ... } ``` -------------------------------- ### Exhaustive Testing Store Source: https://github.com/juavazmor/pointfree-docs-consolidated/blob/main/swift-composable-architecture-docs.md Demonstrates setting up a TestStore in exhaustive mode, where `$0` represents the state *before* an action is sent. This is the default behavior. ```swift let store = TestStore(/* ... */) // ℹ️ "on" is the default so technically this is not needed store.exhaustivity = .on store.send(.buttonTapped) { // $0 represents the state *before* the action was sent $0 } ```