### TestStore Setup with Test Scheduler (Swift) Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0195-tca-concurrency-pt1/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Illustrates setting up a `TestStore` for testing application features. It highlights the use of a `DispatchQueue.test` scheduler for controllable test execution and provides a mocked `numberFact` effect, mirroring the environment setup of a live store but with test-friendly dependencies. ```swift let mainQueue = DispatchQueue.test let store = TestStore( initialState: AppState(), reducer: appReducer, environment: AppEnvironment( mainQueue: mainQueue.eraseToAnyScheduler(), numberFact: { number in Effect(value: "\(number) is a good number Brent") } ) ) ``` -------------------------------- ### Constructing App Store with Dependencies in Swift Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0202-reducer-protocol-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md This snippet demonstrates how to initialize an App's store by providing necessary dependencies, including a network call for fetching number facts. It highlights the main application entry point and the environment setup for handling side effects. ```swift @main struct CaseStudiesApp: App { var body: some Scene { AppView( store: Store( initialState: AppState(), reducer: appReducer, environment: AppEnvironment( numberFact: { number in let (data, _) = try await URLSession.shared .data(from: .init(string: "http://numbersapi.com/\(number)")!) return String(decoding: data, using: UTF8.self) } ) ) ) } } ``` -------------------------------- ### Swift: Construct App Store with Dependencies Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0206-reducer-protocol-pt6/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Constructs the main application store, injecting dependencies like a network endpoint for fetching number facts. This setup is typically done at the app's entry point. ```swift @main struct CaseStudiesApp: App { var body: some Scene { AppView( store: Store( initialState: AppState(), reducer: appReducer, environment: AppEnvironment( numberFact: { number in let (data, _) = try await URLSession.shared .data(from: .init(string: "http://numbersapi.com/(number)")!) return String(decoding: data, using: UTF8.self) } ) ) ) } } ``` -------------------------------- ### Swift: Live Dependency Implementation Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0260-observable-architecture-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Provides an example of a live dependency implementation for a Swift application, specifically fetching a number fact from an external API. ```swift @main struct MyApp: App { var body: some Scene { FeatureView( store: Store(initialState: Feature.State()) { Feature( numberFact: { number in let (data, _) = try await URLSession.shared.data( from: .init(string: "http://numbersapi.com/(number)")! ) return String(decoding: data, as: UTF8.self) } ) } ) } } ``` -------------------------------- ### App Entry Point Configuration with Store in Swift Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0257-macro-case-paths-pt1/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md This Swift code snippet demonstrates the application's entry point using the `@main` attribute. It configures the main scene by creating a `FeatureView` and initializing its `Store` with an initial state and a reducer. This setup is crucial for bootstrapping the application's state management. ```swift @main struct MyApp: App { var body: some Scene { FeatureView( store: Store(initialState: Feature.State()) { Feature() } ) } } ``` -------------------------------- ### Swift: Implementing Live and Mocked Dependencies in Features Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0278-shared-state-in-practice-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Provides examples of how to define a feature's dependency (e.g., `numberFact`) and how to provide both a live implementation (using URLSession) and a mock implementation for testing. ```swift @Reducer struct Feature { let numberFact: (Int) async throws -> String // ... var body: some Reducer { Reduce { state, action in switch action { case .numberFactButtonTapped: return .run { [count = state.count] send in let fact = try await self.numberFact(count) await send(.numberFactResponse(fact)) } // ... } } } } ``` ```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) } ) } ) } } } ``` -------------------------------- ### Providing Live Dependencies in Application Entry Point Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0258-macro-case-paths-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Shows how to provide the live implementation of a dependency when initializing a Store in the application's main entry point. ```swift @main struct MyApp: App { var body: some Scene { FeatureView( store: Store(initialState: Feature.State()) { Feature( numberFact: { number in let (data, _) = try await URLSession.shared.data( from: .init(string: "http://numbersapi.com/\(number)")! ) return String(decoding: data, as: UTF8.self) } ) } ) } } ``` -------------------------------- ### Swift: Implementing Live and Mocked Dependencies Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0257-macro-case-paths-pt1/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Provides examples of implementing both the live (API-calling) and mocked (deterministic) versions of a dependency, such as `numberFact`, for use in the application and in tests respectively. ```swift // Live dependency in application entry point @main struct MyApp: App { var body: some Scene { FeatureView( store: Store(initialState: Feature.State()) { Feature( numberFact: { number in let (data, _) = try await URLSession.shared.data( from: .init(string: "http://numbersapi.com/\(number)")! ) return String(decoding: data, as: UTF8.self) } ) } ) } } // Mock dependency in tests @MainActor func testFeature() async { let store = TestStore(initialState: Feature.State()) { Feature(numberFact: { "\($0) is a good number Brent" }) } } ``` -------------------------------- ### Swift: App Entry Point Without Dependency Construction Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0258-macro-case-paths-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md This Swift code showcases the application's main entry point using the Composable Architecture. It highlights how the main `App` struct no longer needs to manually construct dependencies for the feature's reducer, simplifying the application setup. The live dependencies are automatically provided by the environment. ```swift import ComposableArchitecture import SwiftUI @main struct MyApp: App { var body: some Scene { WindowGroup { FeatureView( store: Store(initialState: Feature.State()) { Feature() } ) } } } ``` -------------------------------- ### Swift: Mocked Dependency for Test Initialization Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0260-observable-architecture-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Shows how to initialize a TestStore with a mocked dependency, providing a deterministic response for testing purposes. ```swift @MainActor func testFeature() async { let store = TestStore(initialState: Feature.State()) { Feature(numberFact: { "\($0) is a good number Brent" }) } } ``` -------------------------------- ### Swift: Completing Feature Test Flow Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0260-observable-architecture-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Demonstrates the final steps in testing a Swift feature, including simulating user interaction, receiving a response, and dismissing an alert. ```swift await store.send(.numberFactButtonTapped) await store.receive(\.numberFactResponse) { $0.numberFactAlert = "0 is a good number Brent" } await store.send(.factAlertDismissed) { $0.numberFactAlert = nil } ``` -------------------------------- ### Swift TestStore Setup for Counter Feature Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0258-macro-case-paths-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/TreeBasedNavigation.md Illustrates the initial setup of a TestStore for the Feature reducer, starting with a specific initial state for the counter. This demonstrates how to configure the TestStore with an initial state and the reducers it should manage, a crucial step for writing effective tests. ```swift func testDismissal() { let store = TestStore( initialState: Feature.State( counter: CounterFeature.State(count: 3) ) ) { CounterFeature() } } ``` -------------------------------- ### Define User Struct and Input Data Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0183-parser-printers-pt6/swift-parsing/Sources/Parsing/Documentation.docc/Articles/GettingStarted.md Initializes the User struct and the input string containing user data to be parsed. This sets up the data structure and the source material for the parsing examples. ```swift let input = """ 1,Blob,true 2,Blob Jr.,false 3,Blob Sr.,true " struct User { var id: Int var name: String var isAdmin: Bool } ``` -------------------------------- ### Swift: Registering Live Dependencies with DependencyKey Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0262-observable-architecture-pt4/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Illustrates how to wrap a dependency in a struct and register its live implementation using a DependencyKey. This makes the dependency globally accessible in the application. ```swift struct NumberFactClient { var fetch: (Int) async throws -> String } private enum NumberFactClientKey: DependencyKey { static let liveValue = NumberFactClient( fetch: { number in let (data, _) = try await URLSession.shared.data( from: .init(string: "http://numbersapi.com/\(number)")! ) return String(decoding: data, as: UTF8.self) } ) } extension DependencyValues { var numberFact: NumberFactClient { get { self[NumberFactClientKey.self] } set { self[NumberFactClientKey.self] = newValue } } } @Reducer struct Feature { @Dependency(\.numberFact) var numberFact // ... } ``` -------------------------------- ### Swift: Mocking Dependencies for Testable Reducers Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0257-macro-case-paths-pt1/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Shows how to make a reducer testable by injecting a dependency, such as a function for fetching a number fact. This example demonstrates providing a mock dependency during test initialization. ```swift struct Feature: Reducer { let numberFact: (Int) async throws -> String // ... } @MainActor func testFeature() async { let store = TestStore(initialState: Feature.State()) { Feature(numberFact: { "\($0) is a good number Brent" }) } } ``` -------------------------------- ### Add Composable Architecture Dependency in SwiftPM Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0202-reducer-protocol-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Integrates the Composable Architecture into a SwiftPM project by adding its URL to the package dependencies and specifying the 'ComposableArchitecture' product for the target. Ensure you have a SwiftPM project setup. ```swift let package = Package( dependencies: [ .package( url: "https://github.com/pointfreeco/swift-composable-architecture", from: "0.39.0" ), ], targets: [ .target( name: "", dependencies: [ .product( name: "ComposableArchitecture", package: "swift-composable-architecture" ) ] ) ] ) ``` -------------------------------- ### Swift: Initialize and Use TestStore for Feature Testing Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0262-observable-architecture-pt4/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Demonstrates initializing a TestStore with a feature's initial state and reducer. It shows how to send actions and assert state changes to simulate user flows. ```swift @MainActor func testFeature() 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 } await store.send(.numberFactButtonTapped) await store.receive(\.numberFactResponse) { $0.numberFactAlert = "???!" } await store.send(.numberFactButtonTapped) await store.receive(\.numberFactResponse) { $0.numberFactAlert = "0 is a good number Brent" } await store.send(.factAlertDismissed) { $0.numberFactAlert = nil } ``` -------------------------------- ### Swift: App Entry Point Without Explicit Dependencies Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0273-shared-state-pt6/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Shows the simplified application entry point using the Composable Architecture. The `Store` is initialized with a `Feature` reducer without needing to manually construct or pass any dependencies. ```swift import SwiftUI import ComposableArchitecture @main struct MyApp: App { var body: some Scene { WindowGroup { FeatureView( store: Store(initialState: Feature.State()) { Feature() } ) } } } ``` -------------------------------- ### Define NumberFactClient and DependencyKey Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0274-shared-state-pt7/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Demonstrates wrapping a dependency (like fetching a number fact) into a dedicated client struct and conforming it to the `DependencyKey` protocol. This sets up the dependency for the 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) } ) } ``` -------------------------------- ### Swift: Registering Live Dependency Implementation Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0260-observable-architecture-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Illustrates how to register a live dependency implementation, like NumberFactClient, with a dependency management system, similar to SwiftUI's environment values. ```swift private enum NumberFactClientKey: DependencyKey { static let liveValue = NumberFactClient( fetch: { number in let (data, _) = try await URLSession.shared.data( from: .init(string: "http://numbersapi.com/(number)")! ) return String(decoding: data, as: UTF8.self) } ) } extension DependencyValues { var numberFact: NumberFactClient { get { self[NumberFactClientKey.self] } set { self[NumberFactClientKey.self] = newValue } } } ``` -------------------------------- ### Swift: Mocking Dependencies for Testing Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0260-observable-architecture-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Demonstrates how to mock external dependencies, like network requests, within a Swift feature reducer to enable predictable and isolated testing. ```swift @Reducer struct Feature { let numberFact: (Int) async throws -> String // ... } case .numberFactButtonTapped: return .run { [count = state.count] send in let fact = try await self.numberFact(count) await send(.numberFactResponse(fact)) } ``` -------------------------------- ### Create and Initialize TestStore in Swift Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0257-macro-case-paths-pt1/swift-composable-architecture/README.md Demonstrates the creation of a TestStore with initial state and a feature reducer. This is the starting point for testing a feature's lifecycle and state changes. ```swift @MainActor func testFeature() async { let store = TestStore(initialState: Feature.State()) { Feature() } } ``` -------------------------------- ### Handle and Assert on Received Effects in Swift Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0266-observable-architecture-pt8/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Illustrates how to simulate sending an action that triggers an effect, then receive and assert on the response from that effect, updating the state accordingly. ```swift await store.send(.numberFactButtonTapped) await store.receive(\.numberFactResponse) { $0.numberFactAlert = "??Cult?" } ``` -------------------------------- ### Swift: Providing Live and Mock Dependencies in Application Entry Point Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0270-shared-state-pt3/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Demonstrates how to provide both live and mock implementations of dependencies. The live dependency is used when running the application, while a mock dependency is provided for testing scenarios, ensuring predictable outcomes. ```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) } ) } ) } } } // Mock dependency for tests @MainActor func testFeature() async { let store = TestStore(initialState: Feature.State()) { Feature(numberFact: { "\($0) is a good number Brent" }) } } ``` -------------------------------- ### Swift: Registering Dependencies with DependencyKey Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0257-macro-case-paths-pt1/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Demonstrates how to create a `DependencyKey` to register a custom dependency, like `NumberFactClient`, with the system. This allows the dependency to be accessed globally and provides a way to define its live implementation. ```swift struct NumberFactClient { var fetch: (Int) async throws -> String } private enum NumberFactClientKey: DependencyKey { static let liveValue = NumberFactClient( fetch: { number in let (data, _) = try await URLSession.shared.data( from: .init(string: "http://numbersapi.com/\(number)")! ) return String(decoding: data, as: UTF8.self) } ) } extension DependencyValues { var numberFact: NumberFactClient { get { self[NumberFactClientKey.self] } set { self[NumberFactClientKey.self] = newValue } } } ``` -------------------------------- ### Define Feature Environment in Swift Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0202-reducer-protocol-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Defines the environment or dependencies required by a feature using a Swift struct. This example includes an asynchronous function to fetch a number fact, which can throw errors. ```swift struct AppEnvironment { var numberFact: (Int) async throws -> String } ``` -------------------------------- ### Swift: Test Store with Overridden Dependencies Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0273-shared-state-pt6/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Illustrates how to construct a `TestStore` for testing features in the Composable Architecture. Dependencies can be left to their default test implementations or explicitly overridden for specific test scenarios. ```swift import ComposableArchitecture // Assume Feature.State and Feature reducer are defined elsewhere let store = TestStore(initialState: Feature.State()) { Feature() } withDependencies: { // Override the numberFact dependency for this test $0.numberFact.fetch = { "\($0) is a good number Brent" } } // Example of asserting a state change or effect run based on the overridden dependency // await store.send(.someAction(count: 42)) // await store.finish() ``` -------------------------------- ### Mocking Dependencies in Feature Reducers for Testing Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0258-macro-case-paths-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Illustrates how to inject mock dependencies into a feature reducer for testing purposes, allowing for deterministic behavior and isolation from external services. ```swift struct Feature: Reducer { let numberFact: (Int) async throws -> String // ... case .numberFactButtonTapped: return .run { [count = state.count] send in let fact = try await self.numberFact(count) await send(.numberFactResponse(fact)) } } ``` ```swift @MainActor func testFeature() async { let store = TestStore(initialState: Feature.State()) { Feature(numberFact: { "\($0) is a good number Brent" }) } await store.send(.numberFactButtonTapped) await store.receive(.numberFactResponse("0 is a good number Brent")) { $0.numberFactAlert = "0 is a good number Brent" } await store.send(.factAlertDismissed) { $0.numberFactAlert = nil } } ``` -------------------------------- ### App Initialization with Mocked Dependencies (Swift) Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0195-tca-concurrency-pt1/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Demonstrates how to initialize the main application view with a `Store`. This includes setting up the initial state, the reducer, and the environment, crucially providing a mocked `numberFact` effect that returns a predefined string, enabling isolated development. ```swift let appView = AppView( store: Store( initialState: AppState(), reducer: appReducer, environment: AppEnvironment( mainQueue: .main, numberFact: { number in Effect(value: "\(number) is a good number Brent") } ) ) ) ``` -------------------------------- ### Swift: Initialize and Use TestStore for State Assertions Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0257-macro-case-paths-pt1/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Demonstrates initializing a TestStore with an initial state and a feature reducer. It then shows how to send actions and assert expected state changes for user interactions like button taps. ```swift @MainActor func testFeature() 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 } } ``` -------------------------------- ### SwiftUI View with Composable Architecture Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0196-tca-concurrency-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md A SwiftUI view integrated with the Composable Architecture, demonstrating button actions that send events to a view store and an alert presentation based on state. ```swift Button("+") { viewStore.send(.incrementButtonTapped) } } Button("Number fact") { viewStore.send(.numberFactButtonTapped) } } .alert( item: viewStore.binding( get: { $0.numberFactAlert.map(FactAlert.init(title:)) }, send: .factAlertDismissed ), content: { Alert(title: Text($0.title)) } ) } } } struct FactAlert: Identifiable { var title: String var id: String { self.title } } ``` -------------------------------- ### Swift: Test Asynchronous Operations with TestStore Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0260-observable-architecture-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Illustrates testing asynchronous operations, like API calls, using TestStore by sending an action and then receiving and asserting the expected response. ```swift await store.send(.numberFactButtonTapped) await store.receive(\.numberFactResponse) { $0.numberFactAlert = "??ư" } ``` -------------------------------- ### Swift: Composable Architecture App Entry Point Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0269-shared-state-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md This Swift code sets up the main application structure using the Composable Architecture and SwiftUI. It defines the root `App` and `WindowGroup`, initializing the `FeatureView` with a `Store`. Dependencies include `ComposableArchitecture` and `SwiftUI`. ```swift import ComposableArchitecture @main struct MyApp: App { var body: some Scene { WindowGroup { FeatureView( store: Store(initialState: Feature.State()) { Feature() } ) } } } ``` -------------------------------- ### Swift Reducer Implementation Using Injected Dependency Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0261-observable-architecture-pt3/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Provides an example of how a Swift reducer's case can utilize an injected dependency (numberFact) to perform an asynchronous operation and send a response. ```swift case .numberFactButtonTapped: return .run { [count = state.count] send in let fact = try await self.numberFact(count) await send(.numberFactResponse(fact)) } ``` -------------------------------- ### Define NumberFactClient and DependencyKey for Dependency Management Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0275-shared-state-pt8/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Shows how to define a client for a specific dependency (NumberFactClient) and conform it to DependencyKey. This enables easy registration and access to live and mock implementations within the application's dependency graph. ```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 } } } ``` -------------------------------- ### Basic Swift App Entry Point Structure Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0278-shared-state-in-practice-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/SharingState.md A foundational Swift structure for an application's main entry point. This example shows a basic setup before optimizations for previews and testing are applied. ```swift @main struct MainApp: App { let store = Store(…) var body: some Scene { … } } ``` -------------------------------- ### App Entry Point with Store and Environment Setup (Swift) Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0202-reducer-protocol-pt2/swift-composable-architecture/README.md This Swift code demonstrates the application's entry point, setting up the main store with initial state, a reducer, and the environment. The environment includes a dependency for fetching a number fact, which is an asynchronous operation using URLSession. ```swift @main struct CaseStudiesApp: App { var body: some Scene { AppView( store: Store( initialState: AppState(), reducer: appReducer, environment: AppEnvironment( numberFact: { number in let (data, _) = try await URLSession.shared .data(from: .init(string: "http://numbersapi.com/\(number)")!) return String(decoding: data, using: UTF8.self) } ) ) ) } } ``` -------------------------------- ### Testing Effects and Received Responses with TestStore Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0258-macro-case-paths-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Shows how to test asynchronous operations (effects) and their subsequent responses within a TestStore, including updating state based on received data. ```swift await store.send(.numberFactButtonTapped) await store.receive(.numberFactResponse("???")) { $0.numberFactAlert = "???" } ``` -------------------------------- ### Swift: Composable Architecture App Entry Point Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0276-shared-state-pt9/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Configures the main application entry point using the Composable Architecture. It specifies the initial state and the reducer for the application's root feature, and presents the main view. ```swift import ComposableArchitecture @main struct MyApp: App { var body: some Scene { WindowGroup { FeatureView( store: Store(initialState: Feature.State()) { // Specify initial state Feature() // Provide the reducer } ) } } } ``` -------------------------------- ### Add Composable Architecture Dependency (SwiftPM) Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0268-shared-state-pt1/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md This snippet demonstrates how to add the Composable Architecture as a dependency in a SwiftPM project's Package.swift file. It specifies the repository URL and version, and then includes the ComposableArchitecture product in a target's dependencies. ```swift let package = Package( dependencies: [ .package( url: "https://github.com/pointfreeco/swift-composable-architecture", from: "1.0.0" ) ], targets: [ .target( name: "", dependencies: [ .product( name: "ComposableArchitecture", package: "swift-composable-architecture" ) ] ) ] ) ``` -------------------------------- ### Setting up Application Entry Point Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0257-macro-case-paths-pt1/swift-composable-architecture/README.md Shows the application's entry point (`@main` struct) where the `FeatureView` is initialized with a `Store`. Dependencies are implicitly provided by the runtime. ```swift @main struct MyApp: App { var body: some Scene { WindowGroup { FeatureView( store: Store(initialState: Feature.State()) { Feature() } ) } } } ``` -------------------------------- ### Test Swift Feature State Changes with TestStore Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0277-shared-state-in-practice-pt1/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Demonstrates how to initialize a TestStore for a feature and send actions to assert state changes. This is crucial for verifying individual user interactions within a feature. ```swift @MainActor func testFeature() async { let store = TestStore(initialState: Feature.State()) { Feature() } } ``` ```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 } ``` ```swift await store.send(.numberFactButtonTapped) await store.receive(.numberFactResponse) { $0.numberFact = ??? } ``` -------------------------------- ### Initialize TestStore for Feature (Swift) Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0275-shared-state-pt8/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/Testing.md Initializes a `TestStore` for the `Feature` reducer with a starting state. This is the basic setup required before sending actions or asserting effects in a test case. ```swift @MainActor class TimerTests: XCTestCase { func testBasics() async { let store = TestStore( initialState: Feature.State(count: 0)) { Feature() } // ... test assertions will follow } } ``` -------------------------------- ### Swift: Initialize AppView Store with Number Fact Dependency Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0203-reducer-protocol-pt3/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Initializes the main AppView store, providing a concrete implementation for the `numberFact` environment dependency. This implementation fetches data from a remote URL. ```swift @main struct CaseStudiesApp: App { var body: some Scene { AppView( store: Store( initialState: AppState(), reducer: appReducer, environment: AppEnvironment( numberFact: { number in let (data, _) = try await URLSession.shared .data(from: .init(string: "http://numbersapi.com/\(number)")!) return String(decoding: data, using: UTF8.self) } ) ) ) } ``` -------------------------------- ### Test Store Initialization with Mocked Dependency Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0274-shared-state-pt7/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Shows how to initialize the `TestStore` in a test function, providing a mock implementation for the `numberFact` dependency. This mock returns a predictable, hardcoded string, ensuring test consistency. ```swift @MainActor func testFeature() async { let store = TestStore(initialState: Feature.State()) { Feature(numberFact: { "\($0) is a good number Brent" }) } await store.send(.numberFactButtonTapped) await store.receive(\.numberFactResponse) { $0.numberFact = "0 is a good number Brent" } } ``` -------------------------------- ### Create and Use TestStore for Feature Testing Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0275-shared-state-pt8/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Demonstrates creating a TestStore for a feature and sending actions to simulate user interactions. It shows how to assert state changes after each action is sent. Dependencies are injected during TestStore initialization. ```swift @MainActor func testFeature() async { let store = TestStore(initialState: Feature.State()) { Feature(numberFact: { "\($0) is a good number Brent" }) } // 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 } // Simulate user tapping fact button and receiving response await store.send(.numberFactButtonTapped) await store.receive(\.numberFactResponse) { $0.numberFact = "0 is a good number Brent" } } ``` -------------------------------- ### Swift: Initialize TestStore with Mocked Number Fact Dependency Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0203-reducer-protocol-pt3/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Initializes a `TestStore` for testing purposes. It replaces the real `numberFact` dependency with a mock implementation that returns a controlled string. ```swift func testFeature() async { let store = TestStore( initialState: AppState(), reducer: appReducer, environment: AppEnvironment( numberFact: { "\($0) is a good number Brent" } ) ) } ``` -------------------------------- ### Swift: Test Store Initialization with Overridable Dependencies Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0270-shared-state-pt3/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Shows how to initialize a TestStore for a feature in the Composable Architecture. It highlights the ability to construct the store without specifying dependencies by default, while also allowing for specific dependency overrides for testing purposes. ```swift let store = TestStore(initialState: Feature.State()) { Feature() } withDependencies: { $0.numberFact.fetch = { "\($0) is a good number Brent" } } ``` -------------------------------- ### Swift TestStore Handling Effects and Receiving Responses Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0261-observable-architecture-pt3/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Shows how to test asynchronous operations in Swift by sending an action that triggers an effect, and then asserting the received response updates the state. ```swift await store.send(.numberFactButtonTapped) await store.receive(\.numberFactResponse) { $0.numberFactAlert = "???" } ``` -------------------------------- ### Point-Free User Parsing with `User.init` (Swift) Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0184-parser-printers-pt7/swift-parsing/Sources/Parsing/Documentation.docc/Articles/GettingStarted.md Presents a more idiomatic Swift approach using a point-free style by passing the `User.init` directly to `Parse` and transforming the `Substring` to `String` using `.map(String.init)`. ```swift let user = Parse(User.init(id:name:isAdmin:)) { Int.parser() "," Prefix { $0 != "," }.map(String.init) "," Bool.parser() } try user.parse(&input) // User(id: 1, name: "Blob", isAdmin: true) input // "\n2,Blob Jr.,false\n3,Blob Sr.,true" ``` -------------------------------- ### Register NumberFactClient as a DependencyKey Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0272-shared-state-pt5/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Conforms `NumberFactClient` to the `DependencyKey` protocol, defining its `liveValue`. This makes the client available globally within the application and provides its real-world implementation using URLSession. ```swift 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) } ) } ``` -------------------------------- ### Creating a Test Store with Mocked Dependencies in Swift Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0202-reducer-protocol-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md This code illustrates the creation of a `TestStore` for unit testing. It shows how to provide mock implementations for dependencies, such as the `numberFact` function, to simulate real-world scenarios without actual network requests. ```swift func testFeature() async { let store = TestStore( initialState: AppState(), reducer: appReducer, environment: AppEnvironment( numberFact: { "\($0) is a good number Brent" } ) ) } ``` -------------------------------- ### Mocking Dependencies for Swift Feature Testing Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0277-shared-state-in-practice-pt1/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Illustrates how to refactor a Swift feature to accept a dependency and provide a mock implementation for testing. This allows for deterministic test outcomes, independent of external services. ```swift @Reducer struct Feature { let numberFact: (Int) async throws -> String // ... } case .numberFactButtonTapped: return .run { [count = state.count] send in let fact = try await self.numberFact(count) await send(.numberFactResponse(fact)) } ``` ```swift @MainActor func testFeature() async { let store = TestStore(initialState: Feature.State()) { Feature(numberFact: { "\($0) is a good number Brent" }) } } await store.send(.numberFactButtonTapped) await store.receive(.numberFactResponse) { $0.numberFact = "0 is a good number Brent" } ``` -------------------------------- ### SwiftUI App Entry Point with Composable Architecture Store Initialization Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0268-shared-state-pt1/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md This Swift code demonstrates the main application entry point using SwiftUI and the Composable Architecture. It sets up the main window group and initializes the FeatureView with a Composable Architecture store, specifying the initial state and reducer. Dependencies include the ComposableArchitecture framework. ```swift import ComposableArchitecture @main struct MyApp: App { var body: some Scene { WindowGroup { FeatureView( store: Store(initialState: Feature.State()) { // Feature() } ) } } } ``` -------------------------------- ### Swift: Asserting on Effect Responses with TestStore Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0257-macro-case-paths-pt1/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Illustrates how to use TestStore to simulate an action that triggers an effect, and then assert on the expected response from that effect and subsequent state changes, such as displaying an alert. ```swift await store.send(.numberFactButtonTapped) await store.receive(.numberFactResponse("???")) { $0.numberFactAlert = "???” } ``` -------------------------------- ### Testing a Feature with Overridden Dependencies (Swift) Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0269-shared-state-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md This Swift code illustrates how to create a `TestStore` for a feature. It shows initializing the store with the feature and then overriding a specific dependency (`numberFact.fetch`) for the test, demonstrating flexible testing capabilities. ```swift import ComposableArchitecture // Assuming Feature and Feature.State are defined elsewhere let store = TestStore(initialState: Feature.State()) { Feature() } withDependencies: { $0.numberFact.fetch = { "\($0) is a good number Brent" } } // ... test logic would follow ``` -------------------------------- ### App Entry Point with FeatureView Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0266-observable-architecture-pt8/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md This Swift code snippet shows the main entry point of an application using the Composable Architecture. It initializes a FeatureView with a Store, setting the initial state and providing the Feature reducer. Dependencies are implicitly handled. ```swift import ComposableArchitecture @main struct MyApp: App { var body: some Scene { FeatureView( store: Store(initialState: Feature.State()) { Feature() } ) } } ``` -------------------------------- ### SwiftUI: Feature View Implementation Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0260-observable-architecture-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md A SwiftUI `View` that displays a feature managed by the Composable Architecture. It uses `WithViewStore` to observe state changes and send actions, including handling an alert presentation. ```swift struct FeatureView: View { let store: StoreOf var body: some View { WithViewStore(self.store, observe: { $0 }) { viewStore in VStack { HStack { Button("−") { viewStore.send(.decrementButtonTapped) } Text("\(viewStore.count)") Button("+") { viewStore.send(.incrementButtonTapped) } } Button("Number fact") { viewStore.send(.numberFactButtonTapped) } } .alert( item: viewStore.binding( get: { $0.numberFactAlert.map(FactAlert.init(title:)) }, send: .factAlertDismissed ), content: { Alert(title: Text($0.title)) } ) } } } ``` -------------------------------- ### Swift: Constructing a Test Store with Overridden Dependencies Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0257-macro-case-paths-pt1/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Demonstrates how to create a `TestStore` for testing a feature. It shows the basic construction and how to override a specific dependency, such as the `numberFact` dependency, to control its behavior during tests. ```swift let store = TestStore( initialState: Feature.State() ) { Feature() } withDependencies: { $0.numberFact.fetch = { "\($0) is a good number Brent" } } await store.send(.numberFactButtonTapped) await store.receive(.numberFactResponse("0 is a good number Brent")) { $0.numberFactAlert = "0 is a good number Brent" } ``` -------------------------------- ### TestStore Initialization and Dependency Override Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0260-observable-architecture-pt2/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md This Swift code illustrates how to create a `TestStore` for testing features in the Composable Architecture. It initializes the store with the feature's state and reducer, and allows for overriding specific dependencies, such as the `fetch` function for number facts. ```swift let store = TestStore(initialState: Feature.State()) { Feature() } withDependencies: { $0.numberFact.fetch = { "\($0) is a good number Brent" } } await store.send(.numberFactButtonTapped) await store.receive(\.numberFactResponse) { $0.numberFactAlert = "0 is a good number Brent" } ``` -------------------------------- ### Swift: Completing a Test Flow with Dismissal Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0257-macro-case-paths-pt1/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Illustrates the final steps in a TestStore scenario, including sending an action to dismiss an alert and asserting that the relevant state property is reset to nil. ```swift await store.send(.numberFactButtonTapped) await store.receive(.numberFactResponse("0 is a good number Brent")) { $0.numberFactAlert = "0 is a good number Brent" } await store.send(.factAlertDismissed) { $0.numberFactAlert = nil } ``` -------------------------------- ### Parsing Multiple Users with `Many` (Swift) Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0184-parser-printers-pt7/swift-parsing/Sources/Parsing/Documentation.docc/Articles/GettingStarted.md Demonstrates how to parse a list of users from the input string using the `Many` parser, specifying the `user` parser and the newline separator. ```swift let users = Many { user } separator: { "\n" } try users.parse(&input) // [User(id: 1, name: "Blob", isAdmin: true), ...] input // "" ``` -------------------------------- ### SwiftUI: Create AppView with Store and actions Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0199-tca-concurrency-pt5/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Defines the SwiftUI view for a feature, holding a Store to observe state changes and send actions. It displays the count and buttons to interact with the feature. ```swift struct AppView: View { let store: Store var body: some View { WithViewStore(self.store) { viewStore in VStack { HStack { Button("−") { viewStore.send(.decrementButtonTapped) } Text("\(viewStore.count)") ``` -------------------------------- ### TCA Application Entry Point Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0266-observable-architecture-pt8/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Defines the main application structure using `@main` and SwiftUI's `App` protocol. This snippet demonstrates how to initialize the TCA `Store` with initial state and a reducer, and then present the root view. ```swift @main struct MyApp: App { var body: some Scene { FeatureView( store: Store(initialState: Feature.State()) { Feature() } ) } } ``` -------------------------------- ### Swift: Mocking a Dependency for Testable Reducers Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0262-observable-architecture-pt4/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Shows how to refactor a reducer to accept a dependency (like an API client) and provide a mock implementation during testing. This ensures deterministic test results. ```swift @Reducer struct Feature { let numberFact: (Int) async throws -> String // ... } case .numberFactButtonTapped: return .run { let fact = try await self.numberFact(count) await send(.numberFactResponse(fact)) } @MainActor func testFeature() async { let store = TestStore(initialState: Feature.State()) { Feature(numberFact: { "\($0) is a good number Brent" }) } } ``` -------------------------------- ### Swift: Test Store Interactions and State Changes Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0203-reducer-protocol-pt3/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Demonstrates testing a user flow within the Composable Architecture. It includes sending actions, asserting state changes after increments/decrements, handling asynchronous responses from effects, and dismissing alerts. ```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 } // Test that tapping the fact button causes us to receive a response from the effect. Note // that we have to await the receive because the effect is asynchronous and so takes a small // amount of time to emit. await store.send(.numberFactButtonTapped) await store.receive(.numberFactResponse(.success("0 is a good number Brent"))) { $0.numberFactAlert = "0 is a good number Brent" } // And finally dismiss the alert await store.send(.factAlertDismissed) { $0.numberFactAlert = nil } ``` -------------------------------- ### Swift App Entry Point with FeatureView Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0262-observable-architecture-pt4/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md This Swift code defines the main application struct and initializes a FeatureView with a Store. The Store is configured with an initial state and a Feature reducer, showcasing a typical application entry point in the Composable Architecture. It highlights how dependencies are implicitly provided. ```swift struct MyApp: App { var body: some Scene { FeatureView( store: Store(initialState: Feature.State()) { Feature() } ) } } ``` -------------------------------- ### SwiftUI View for Feature Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0277-shared-state-in-practice-pt1/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md A SwiftUI view that displays the feature's state and allows users to interact with it. It holds a StoreOf to observe state changes and send actions to the store. ```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) } } } } ``` -------------------------------- ### Swift: Register Dependency Client with DependencyKey and DependencyValues Source: https://github.com/pointfreeco/episode-code-samples/blob/main/0264-observable-architecture-pt6/swift-composable-architecture/Sources/ComposableArchitecture/Documentation.docc/Articles/GettingStarted.md Shows how to register a custom dependency client (`NumberFactClient`) with the system's dependency management. This involves defining a `DependencyKey` for the live implementation and extending `DependencyValues` for easy access. ```swift private enum NumberFactClientKey: DependencyKey { static let liveValue = NumberFactClient( fetch: { number in let (data, _) = try await URLSession.shared.data( from: .init(string: "http://numbersapi.com/\(number)")! ) return String(decoding: data, as: UTF8.self) } ) } extension DependencyValues { var numberFact: NumberFactClient { get { self[NumberFactClientKey.self] } set { self[NumberFactClientKey.self] = newValue } } } ```