### Install AppState via Swift Package Manager Source: https://context7.com/0xleif/appstate/llms.txt Add AppState as a dependency in your Package.swift file and build your project. ```swift // Package.swift dependencies: [ .package(url: "https://github.com/0xLeif/AppState.git", from: "2.2.0") ], targets: [ .target( name: "YourTarget", dependencies: ["AppState"]) ] ``` ```bash swift build ``` -------------------------------- ### Define Application Dependencies Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-state-dependency.md Define shared resources or services as dependencies by extending the Application object. This example shows a NetworkServiceType. ```swift import AppState protocol NetworkServiceType { func fetchData() -> String } class NetworkService: NetworkServiceType { func fetchData() -> String { return "Data from network" } } extension Application { var networkService: Dependency { dependency(NetworkService()) } } ``` -------------------------------- ### Define and Access State in SwiftUI Source: https://github.com/0xleif/appstate/blob/main/README.md Demonstrates how to define a state variable within an Application extension and access it using the @AppState property wrapper in a SwiftUI view. Ensure AppState is installed via Swift Package Manager. ```swift import AppState import SwiftUI private extension Application { var counter: State { state(initial: 0) } } struct ContentView: View { @AppState(\.counter) var counter: Int var body: some View { VStack { Text("Count: \(counter)") Button("Increment") { counter += 1 } } } } ``` -------------------------------- ### Define a Constant in Application Extension Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-constant.md Define a `Constant` within an `Application` extension to provide read-only access to a specific piece of state. This setup is required before accessing the constant in views. ```swift import AppState import SwiftUI struct ExampleValue { var username: String? var isLoading: Bool let value: String var mutableValue: String } extension Application { var exampleValue: State { state( initial: ExampleValue( username: "Leif", isLoading: false, value: "value", mutableValue: "" ) ) } } ``` -------------------------------- ### Resetting Persistent State - AppState Source: https://github.com/0xleif/appstate/blob/main/documentation/en/faq.md Use the static `reset` function on the `Application` type to reset persistent states like `StoredState`, `FileState`, and `SyncState` to their initial values. This example shows resetting a `StoredState`. ```swift extension Application { var hasCompletedOnboarding: StoredState { storedState(initial: false, id: "onboarding_complete") } } // Somewhere in your code Application.reset(storedState: \.hasCompletedOnboarding) ``` -------------------------------- ### Resetting Non-Persistent State - AppState Source: https://github.com/0xleif/appstate/blob/main/documentation/en/faq.md Non-persistent `State` values can also be reset to their initial values using the `Application.reset` function. This example demonstrates resetting a `State`. ```swift extension Application { var counter: State { state(initial: 0) } } // Somewhere in your code Application.reset(\.counter) ``` -------------------------------- ### Initialize App with SyncState Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-syncstate.md Configure the application in the @main struct by promoting a custom application, enabling logging, and loading the iCloud store dependency. ```swift @main struct SyncStateExampleApp: App { init() { Application .promote(to: CustomApplication.self) .logging(isEnabled: true) .load(dependency: \.icloudStore) } var body: some Scene { WindowGroup { ContentView() } } } ``` -------------------------------- ### Build Project with Swift Package Manager Source: https://github.com/0xleif/appstate/blob/main/documentation/en/installation.md Execute the `swift build` command in your project's root directory to download and integrate the AppState dependency. ```bash swift build ``` -------------------------------- ### Preloading Dependencies in Swift AppState Source: https://github.com/0xleif/appstate/blob/main/documentation/en/advanced-usage.md Shows how to preload dependencies using the `load` function during application initialization. This ensures dependencies are ready before they are needed. ```swift extension Application { var databaseClient: Dependency { dependency(DatabaseClient()) } } // Preload in app initialization Application.load(dependency: \.databaseClient) ``` -------------------------------- ### Testing AppState with Mock Dependencies Source: https://context7.com/0xleif/appstate/llms.txt This snippet demonstrates how to set up mock dependencies and test AppState features. It includes a mock network service, fileprivate extensions for application dependencies, and an observable service for testing observed dependencies. Use this for unit testing AppState integrations. ```swift import XCTest @testable import AppState // Mock dependency for testing class MockNetworkService: NetworkServiceType { var stubbedResponse = "Mock Data" func fetchData() -> String { stubbedResponse } } fileprivate extension Application { var mockNetwork: Dependency { dependency(MockNetworkService()) } var testCounter: State { state(initial: 0) } } // ObservableObject dependency test @MainActor fileprivate class ObservableService: ObservableObject { @Published var count: Int = 0 } fileprivate extension Application { @MainActor var observableService: Dependency { dependency(ObservableService()) } } @MainActor fileprivate struct ExampleWrapper { @ObservedDependency(\.observableService) var service func increment() { service.count += 1 } } final class AppStateTests: XCTestCase { @MainActor func testObservedDependency() async { let wrapper = ExampleWrapper() XCTAssertEqual(wrapper.service.count, 0) wrapper.increment() XCTAssertEqual(wrapper.service.count, 1) } func testMockNetwork() { let mock = MockNetworkService() mock.stubbedResponse = "Test Response" XCTAssertEqual(mock.fetchData(), "Test Response") } } ``` -------------------------------- ### Initialize AppState for ToDo List Source: https://github.com/0xleif/appstate/wiki/EXAMPLE:-ToDo-List-App-with-AppState Defines the Task structure and extends Application to include a state property for tasks. ```swift struct Task { var name: String var isCompleted: Bool } extension Application { var tasks: State<[Task]> { state(initial: []) } } ``` -------------------------------- ### Define Application State and Dependencies Source: https://context7.com/0xleif/appstate/llms.txt Extend the Application singleton to declare app-wide state and dependencies. Subclass Application to handle lifecycle hooks like iCloud changes. Bootstrap your application with custom configurations. ```swift import AppState // 1. Define all state & dependencies in Application extensions extension Application { var user: State { state(initial: User(name: "Guest", isLoggedIn: false)) } var networkService: Dependency { dependency(NetworkService()) } } // 2. Subclass to handle iCloud external changes class CustomApplication: Application { override func didChangeExternally(notification: Notification) { super.didChangeExternally(notification: notification) DispatchQueue.main.async { self.objectWillChange.send() } } } // 3. Bootstrap in @main @main struct MyApp: App { init() { Application .promote(to: CustomApplication.self) .logging(isEnabled: true) .load(dependency: \.networkService) // preload eagerly } var body: some Scene { WindowGroup { ContentView() } } } ``` -------------------------------- ### Custom Application Subclass with Application.promote(to:) Source: https://context7.com/0xleif/appstate/llms.txt Replace the default `Application.shared` singleton with a custom subclass to override hooks or add bespoke initialization logic. This is done early in the app lifecycle. ```swift import AppState class MyApplication: Application { // Called whenever iCloud pushes an external change override func didChangeExternally(notification: Notification) { super.didChangeExternally(notification: notification) DispatchQueue.main.async { self.objectWillChange.send() } } // Custom extra setup via the required initializer required init(setup: (Application) -> Void = { _ in }) { super.init(setup: setup) // perform additional one-time configuration here } } @main struct MyApp: App { init() { Application .promote(to: MyApplication.self) .logging(isEnabled: true) } var body: some Scene { WindowGroup { ContentView() } } } ``` -------------------------------- ### Custom Decodable Initializer for Data Format Changes Source: https://github.com/0xleif/appstate/blob/main/documentation/en/migration-considerations.md Implement a custom `init(from decoder:)` to handle data format changes, such as type conversions, by providing default values or mapping old data to the new structure. ```swift struct Settings: Codable { var text: String var isDarkMode: Bool var version: Int // Custom decoding logic for older versions init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.text = try container.decode(String.self, forKey: .text) self.isDarkMode = try container.decode(Bool.self, forKey: .isDarkMode) self.version = (try? container.decode(Int.self, forKey: .version)) ?? 1 // Default for older data } } ``` -------------------------------- ### Initialize AppState for Counter Source: https://github.com/0xleif/appstate/wiki/EXAMPLE:-Counter-App-with-AppState Define the counter state within the Application extension. This sets up the initial value for the counter. ```swift extension Application { var counter: State { state(initial: 0) } } ``` -------------------------------- ### Handling Absence of Secure Data Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-securestate.md Demonstrates how to safely access SecureState data, printing a message if no token is available. ```swift if let token = userToken { print("Token: \(token)") } else { print("No token available.") } ``` -------------------------------- ### Clone AppState Repository Source: https://github.com/0xleif/appstate/blob/main/documentation/en/contributing.md Clone your personal fork of the AppState repository to your local machine to begin making changes. ```bash git clone https://github.com/your-username/AppState.git ``` -------------------------------- ### Include AppState in Target Dependencies Source: https://github.com/0xleif/appstate/blob/main/documentation/en/installation.md Specify AppState as a dependency for your specific target within the `Package.swift` file to make it available for use. ```swift .target( name: "YourTarget", dependencies: ["AppState"]) ``` -------------------------------- ### Import AppState in Swift Code Source: https://github.com/0xleif/appstate/blob/main/documentation/en/installation.md Add this import statement at the top of your Swift files to begin using the AppState library. ```swift import AppState ``` -------------------------------- ### Extend Application Singleton with Custom Dependency Source: https://github.com/0xleif/appstate/wiki/Home Extend the Application singleton to include custom dependencies like Network. This allows for global access to these dependencies. ```swift extension Application { public var network: Dependency { dependency(Network()) } } ``` -------------------------------- ### Define Application State and Dependencies Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-overview.md Extend the Application object to define application-wide state and dependencies. This centralizes all app state in one place. ```swift import AppState extension Application { var user: State { state(initial: User(name: "Guest", isLoggedIn: false)) } var userPreferences: StoredState { storedState(initial: "Default Preferences", id: "userPreferences") } var darkModeEnabled: SyncState { syncState(initial: false, id: "darkModeEnabled") } var userToken: SecureState { secureState(id: "userToken") } @MainActor var largeDataset: FileState<[String]> { fileState(initial: [], filename: "largeDataset") } } ``` -------------------------------- ### Preload Dependencies with AppState's Load Function Source: https://github.com/0xleif/appstate/wiki/AppState's-Just‐In‐Time-Creation-of-Values Preload a dependency to ensure it is initialized before being accessed in view code. This is useful for dependencies that require time to initialize or must be available at app startup. ```swift extension Application { var databaseClient: Dependency { dependency(DatabaseClient()) } } // Then somewhere in your app initialization code, you can load the dependency: Application.load(dependency: \.databaseClient) ``` -------------------------------- ### Shared State and Dependencies with Explicit IDs in Swift Source: https://github.com/0xleif/appstate/blob/main/documentation/en/advanced-usage.md Illustrates defining shared state and dependencies using explicit string IDs. Note that this pattern is generally discouraged due to potential ID collisions and reduced maintainability. ```swift private extension Application { var stateValue: State { state(initial: 0, id: "stateValue") } var dependencyValue: Dependency { dependency(SomeType(), id: "dependencyValue") } } ``` ```swift private extension Application { var theSameStateValue: State { state(initial: 0, id: "stateValue") } var theSameDependencyValue: Dependency { dependency(SomeType(), id: "dependencyValue") } } ``` -------------------------------- ### Create Views for State Modification and Sync Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-syncstate.md Use @SyncState and @Slice property wrappers to create views that can modify and display synchronized state. Changes made in one view are reflected in others. ```swift struct ContentView: View { @SyncState(\.settings) private var settings: Settings var body: some View { VStack { TextField("", text: $settings.text) Button(settings.isDarkMode ? "Light" : "Dark") { settings.isDarkMode.toggle() } Button("Show") { settings.isShowingSheet = true } } .preferredColorScheme(settings.isDarkMode ? .dark : .light) .sheet(isPresented: $settings.isShowingSheet, content: ContentViewInnerView.init) } } struct ContentViewInnerView: View { @Slice(\.settings, \.text) private var text: String var body: some View { Text("\(text)") .onTapGesture { text = Date().formatted() } } } ``` -------------------------------- ### Advanced State Management: Scoped IDs & File-Private Access Source: https://context7.com/0xleif/appstate/llms.txt Demonstrates advanced AppState features for managing state uniqueness and scope. This includes just-in-time creation, explicit IDs for cross-module sharing, UUIDs for restricted access, file-private isolation, feature namespaces, and eager dependency loading. ```swift import AppState // --- Just-in-time (default) --- extension Application { var counter: State { state(initial: 0) // instantiated only on first access } } // --- Explicit ID for cross-extension sharing (use sparingly) --- private extension Application { var sharedCount: State { state(initial: 0, id: "sharedCount") } var alsoSharedCount: State { state(initial: 0, id: "sharedCount") // resolves to same cache entry } } // --- UUID-based restricted access --- private extension Application { var secretState: State { state(initial: nil, id: UUID().uuidString) // new entry on every property access — use fixed UUID for persistence } } // --- File-private isolation --- fileprivate extension Application { var filePrivateCounter: State { state(initial: 0) // not accessible outside this file } } // --- Feature namespace (recommended for larger apps) --- extension Application { var profileScore: State { state(initial: 0, feature: "UserProfile", id: "score") } } // --- Preload a dependency eagerly at launch --- extension Application { var analyticsClient: Dependency { dependency(AnalyticsClient()) } } // In @main init(): // Application.load(dependency: \.analyticsClient) ``` -------------------------------- ### Task List View with AppState Source: https://github.com/0xleif/appstate/wiki/EXAMPLE:-ToDo-List-App-with-AppState Displays a list of tasks and provides functionality to add new tasks. Uses @AppState to bind to the tasks state. ```swift struct TaskListView: View { @AppState(\.tasks) var tasks @State private var newTaskName: String = "" var body: some View { List { ForEach(tasks.indices, id: \.self) { index in TaskRowView(task: $tasks[index]) } TextField("New task", text: $newTaskName, onCommit: addTask) } } private func addTask() { tasks.append(Task(name: newTaskName, isCompleted: false)) newTaskName = "" } } ``` -------------------------------- ### Define State with Just-In-Time Creation Source: https://github.com/0xleif/appstate/wiki/AppState's-Just‐In‐Time-Creation-of-Values Define a State property that is instantiated only when first accessed. This optimizes resource usage by delaying creation until needed. ```swift extension Application { var defaultState: State { state(initial: 0) // The value is not created until it's accessed } } ``` -------------------------------- ### Modularizing AppState with Feature Namespaces Source: https://github.com/0xleif/appstate/blob/main/documentation/en/best-practices.md Use the `feature` parameter when defining states to provide a namespace. This helps organize states and prevent ID collisions, especially in larger applications. ```swift state(initial: 0, feature: "UserProfile", id: "score") ``` -------------------------------- ### Define and Use FileState for User Profile Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-filestate.md Define a FileState for a Codable UserProfile struct in your Application extension and access it in a SwiftUI View using @FileState. Updates to the state will persist. ```swift import AppState import SwiftUI struct UserProfile: Codable { var name: String var age: Int } extension Application { @MainActor var userProfile: FileState { fileState(initial: UserProfile(name: "Guest", age: 25), filename: "userProfile") } } struct FileStateExampleView: View { @FileState(\.userProfile) var userProfile: UserProfile var body: some View { VStack { Text("Name: \(userProfile.name), Age: \(userProfile.age)") Button("Update Profile") { userProfile = UserProfile(name: "UpdatedName", age: 30) } } } } ``` -------------------------------- ### Using SyncState for Integer Synchronization Source: https://github.com/0xleif/appstate/blob/main/documentation/en/syncstate-implementation.md Define a SyncState property for integers and use it within a SwiftUI View. Changes to this state are automatically saved to iCloud. ```swift import AppState import SwiftUI extension Application { var syncValue: SyncState { syncState(id: "syncValue") } } struct ContentView: View { @SyncState(\.syncValue) private var syncValue: Int? var body: some View { VStack { if let syncValue = syncValue { Text("SyncValue: \(syncValue)") } else { Text("No SyncValue") } Button("Update SyncValue") { syncValue = Int.random(in: 0..<100) } } } } ``` -------------------------------- ### Commit Changes Source: https://github.com/0xleif/appstate/blob/main/documentation/en/contributing.md Commit your changes with a descriptive message that clearly explains the purpose of the commit. ```bash git commit -m "Add my new feature" ``` -------------------------------- ### Counter View with AppState Source: https://github.com/0xleif/appstate/wiki/EXAMPLE:-Counter-App-with-AppState Create a SwiftUI view to display and interact with the counter state. Use the @AppState property wrapper to access and modify the counter value. Includes buttons for incrementing, decrementing, and resetting. ```swift struct CounterView: View { @AppState(\.counter) var counter var body: some View { VStack { Text("Counter: \(counter)") HStack { Button(action: increment) { Text("Increment") } Button(action: decrement) { Text("Decrement") } Button(action: reset) { Text("Reset") } } } } private func increment() { counter += 1 } private func decrement() { counter -= 1 } private func reset() { counter = 0 } } ``` -------------------------------- ### Bind ObservedDependency to UI Elements Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-observeddependency.md Demonstrates how to bind an observable dependency's state to UI elements like a Picker for reactive updates. Ensure the dependency uses @Published properties. ```swift import AppState import SwiftUI struct ReactiveView: View { @ObservedDependency(\.observableService) var service: ObservableService var body: some View { Picker("Select Count", selection: $service.count) { ForEach(0..<10) { count in Text("\(count)").tag(count) } } } } ``` -------------------------------- ### Public Access Level for State and Dependency Source: https://github.com/0xleif/appstate/wiki/Managing-Application-Access-with-AppState Define States and Dependencies with `public` access to allow access from any part of the application or other modules. ```swift public extension Application { var publicValue: State { state(initial: 0) } var publicDependency: Dependency { dependency(initial: SomeType()) } } ``` -------------------------------- ### Restrict Access with UUID IDs for State and Dependency Source: https://github.com/0xleif/appstate/wiki/Managing-Application-Access-with-AppState Use UUIDs as IDs for States and Dependencies to significantly reduce the possibility of unauthorized access. ```swift private extension Application { var stateValue: State { state(initial: 0, id: UUID().uuidString) } var dependencyValue: Dependency { dependency(SomeType(), id: UUID().uuidString) } } ``` -------------------------------- ### Declare SyncState Property Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-syncstate.md Extend the Application object to declare a SyncState property, providing an initial value and a unique ID. ```swift extension Application { var settings: SyncState { syncState( initial: Settings( text: "Hello, World!", isShowingSheet: false, isDarkMode: false ), id: "settings" ) } } ``` -------------------------------- ### Add AppState Dependency to Package.swift Source: https://github.com/0xleif/appstate/blob/main/documentation/en/installation.md Include AppState as a dependency in your Swift Package Manager project by adding its repository URL and version to the `dependencies` array in your `Package.swift` file. ```swift dependencies: [ .package(url: "https://github.com/0xLeif/AppState.git", from: "2.2.0") ] ``` -------------------------------- ### Push Changes to GitHub Source: https://github.com/0xleif/appstate/blob/main/documentation/en/contributing.md Push your local branch containing your changes to your GitHub fork to make them available for a pull request. ```bash git push origin my-feature-branch ``` -------------------------------- ### Define an Observable Service Dependency Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-observeddependency.md Define an observable service conforming to ObservableObject and register it as a dependency in the Application extension. Use @MainActor for main thread access. ```swift import AppState import SwiftUI @MainActor class ObservableService: ObservableObject { @Published var count: Int = 0 } extension Application { @MainActor var observableService: Dependency { dependency(ObservableService()) } } ``` -------------------------------- ### SyncState for iCloud Synchronization Source: https://context7.com/0xleif/appstate/llms.txt SyncState synchronizes Codable state across devices using NSUbiquitousKeyValueStore. Ensure iCloud Key-Value Store capability is enabled and load \.icloudStore at launch. ```swift import AppState import SwiftUI struct Settings: Codable { var text: String var isShowingSheet: Bool var isDarkMode: Bool } extension Application { var settings: SyncState { syncState( initial: Settings(text: "Hello, World!", isShowingSheet: false, isDarkMode: false), id: "settings" ) } } // Override iCloud change notification in a custom Application subclass: class CustomApplication: Application { override func didChangeExternally(notification: Notification) { super.didChangeExternally(notification: notification) DispatchQueue.main.async { self.objectWillChange.send() } } } @main struct SyncStateApp: App { init() { Application .promote(to: CustomApplication.self) .logging(isEnabled: true) .load(dependency: \.icloudStore) } var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { @SyncState(\.settings) private var settings: Settings var body: some View { VStack { TextField("Message", text: $settings.text) Button(settings.isDarkMode ? "Light Mode" : "Dark Mode") { settings.isDarkMode.toggle() } Button("Show Sheet") { settings.isShowingSheet = true } } .preferredColorScheme(settings.isDarkMode ? .dark : .light) .sheet(isPresented: $settings.isShowingSheet) { // Inner view using Slice to access only the text field InnerView() } } } struct InnerView: View { @Slice(\.settings, \.text) private var text: String var body: some View { Text("\(text)") .onTapGesture { text = Date().formatted() } } } ``` -------------------------------- ### Define Shared State and Dependency with Explicit IDs Source: https://github.com/0xleif/appstate/wiki/Managing-Application-Access-with-AppState Define a State and a Dependency with specific string IDs to enable access from different parts of your application or modules. ```swift private extension Application { var stateValue: State { state(initial: 0, id: "stateValue") } var dependencyValue: Dependency { dependency(SomeType(), id: "stateValue") } } ``` ```swift private extension Application { var theSameStateValue: State { state(initial: 0, id: "stateValue") } var theSameDependencyValue: Dependency { dependency(SomeType(), id: "stateValue") } } ``` -------------------------------- ### Use @StoredState for UserDefaults Persistence Source: https://context7.com/0xleif/appstate/llms.txt Back state with UserDefaults for automatic persistence across app launches. Ideal for non-sensitive data like user preferences and feature flags. ```swift import AppState import SwiftUI extension Application { var userPreferences: StoredState { storedState(initial: "Default Preferences", id: "userPreferences") } var hasOnboarded: StoredState { storedState(initial: false, id: "hasOnboarded") } } struct PreferencesView: View { @StoredState(\.userPreferences) var userPreferences: String @StoredState(\.hasOnboarded) var hasOnboarded: Bool var body: some View { VStack { Text("Preferences: \(userPreferences)") Toggle("Onboarding complete", isOn: $hasOnboarded) Button("Reset Preferences") { userPreferences = "Default Preferences" } Button("Update Preferences") { userPreferences = "Updated Preferences" } } } } ``` -------------------------------- ### Restricted State and Dependency Access with UUIDs in Swift Source: https://github.com/0xleif/appstate/blob/main/documentation/en/advanced-usage.md Demonstrates using UUIDs as unique IDs to restrict access to specific states and dependencies, ensuring only intended parts of the app can access them. ```swift private extension Application { var restrictedState: State { state(initial: nil, id: UUID().uuidString) } var restrictedDependency: Dependency { dependency(SomeType(), id: UUID().uuidString) } } ``` -------------------------------- ### Create New Branch for Changes Source: https://github.com/0xleif/appstate/blob/main/documentation/en/contributing.md Create a new branch for your feature or bugfix to keep your changes organized and separate from the main codebase. ```bash git checkout -b my-feature-branch ``` -------------------------------- ### Combine State and Dependencies in a View Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-state-dependency.md Integrate both @AppState and @AppDependency property wrappers in a SwiftUI view to access shared state and services simultaneously. This allows for complex interactions like fetching data and updating state. ```swift import AppState import SwiftUI struct CombinedView: View { @AppState(\.user) var user: User @AppDependency(\.networkService) var networkService: NetworkServiceType var body: some View { VStack { Text("User: \(user.name)") Button("Fetch Data") { user.name = networkService.fetchData() user.isLoggedIn = true } } } } ``` -------------------------------- ### Define Codable Data Model Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-syncstate.md Define a struct that conforms to Codable to represent the state that will be synchronized. ```swift struct Settings: Codable { var text: String var isShowingSheet: Bool var isDarkMode: Bool } ``` -------------------------------- ### Secure Sensitive Data with SecureState Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-overview.md Leverage @SecureState to securely store sensitive data in the Keychain. This is recommended for credentials or tokens. ```swift import AppState import SwiftUI struct SecureView: View { @SecureState(\.userToken) var userToken: String? var body: some View { VStack { if let token = userToken { Text("User token: \(token)") } else { Text("No token found.") } Button("Set Token") { userToken = "secure_token_value" } } } } ``` -------------------------------- ### Entitlements File Configuration for iCloud Key-Value Store Source: https://github.com/0xleif/appstate/blob/main/documentation/en/syncstate-implementation.md Ensure your entitlements file includes the correct iCloud container identifier for Key-Value storage. ```xml com.apple.developer.ubiquity-kvstore-identifier $(TeamIdentifierPrefix)com.yourdomain.app ``` -------------------------------- ### Default Unique IDs for State and Dependencies in Swift Source: https://github.com/0xleif/appstate/blob/main/documentation/en/advanced-usage.md Shows how AppState automatically generates unique IDs for states and dependencies when no explicit ID is provided, ensuring uniqueness and preventing unintended access. ```swift extension Application { var defaultState: State { state(initial: 0) // AppState generates a unique ID } var defaultDependency: Dependency { dependency(SomeType()) // AppState generates a unique ID } } ``` -------------------------------- ### Internal Access Level for State and Dependency Source: https://github.com/0xleif/appstate/wiki/Managing-Application-Access-with-AppState Use the default `internal` access level to make States and Dependencies accessible only within the same module. ```swift extension Application { var internalValue: State { state(initial: 0) } var internalDependency: Dependency { dependency(initial: SomeType()) } } ``` -------------------------------- ### Synchronize State with SyncState Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-overview.md Employ @SyncState for synchronizing app state across multiple devices using iCloud. This is useful for features that require cross-device consistency. ```swift import AppState import SwiftUI struct SyncSettingsView: View { @SyncState(\.darkModeEnabled) var isDarkModeEnabled: Bool var body: some View { VStack { Toggle("Dark Mode", isOn: $isDarkModeEnabled) } } } ``` -------------------------------- ### Access Dependencies in a SwiftUI View Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-state-dependency.md Use the @AppDependency property wrapper to inject and access dependencies within a SwiftUI view. Ensure AppState is imported. ```swift import AppState import SwiftUI struct NetworkView: View { @AppDependency(\.networkService) var networkService: NetworkServiceType var body: some View { VStack { Text("Data: \(networkService.fetchData())") } } } ``` -------------------------------- ### SecureState for Keychain Storage Source: https://context7.com/0xleif/appstate/llms.txt SecureState encrypts sensitive string values in the Keychain, suitable for tokens, passwords, or keys. It always returns an optional String? as the Keychain might not have a value. ```swift import AppState import SwiftUI extension Application { var userToken: SecureState { secureState(id: "userToken") } var refreshToken: SecureState { secureState(id: "refreshToken") } } struct AuthView: View { @SecureState(\.userToken) var userToken: String? @SecureState(\.refreshToken) var refreshToken: String? var body: some View { VStack { if let token = userToken { Text("Authenticated: \(token.prefix(8))…") Button("Log out") { userToken = nil refreshToken = nil } } else { Text("No token found.") Button("Set Token") { userToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" refreshToken = "dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4" } } } } } ``` -------------------------------- ### Define Application State Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-state-dependency.md Extend the Application object to declare state properties. This centralizes your app's state. ```swift import AppState struct User { var name: String var isLoggedIn: Bool } extension Application { var user: State { state(initial: User(name: "Guest", isLoggedIn: false)) } } ``` -------------------------------- ### Checkbox View for Task Completion Source: https://github.com/0xleif/appstate/wiki/EXAMPLE:-ToDo-List-App-with-AppState A custom CheckBox view that visually represents and toggles the completion status of a task using a system image. ```swift struct CheckBox: View { @Binding var isChecked: Bool var body: some View { Button(action: toggle) { Image(systemName: isChecked ? "checkmark.square" : "square") } } private func toggle() { isChecked.toggle() } } ``` -------------------------------- ### FileState for Persistent State Source: https://context7.com/0xleif/appstate/llms.txt Use FileState to serialize Codable values to disk using FileManager. It's suitable for larger objects like cached datasets or user profiles and must be declared @MainActor. ```swift import AppState import SwiftUI struct UserProfile: Codable { var name: String var age: Int } extension Application { @MainActor var userProfile: FileState { fileState(initial: UserProfile(name: "Guest", age: 25), filename: "userProfile") } @MainActor var largeDataset: FileState<[String]> { fileState(initial: [], filename: "largeDataset") } } struct FileStateExampleView: View { @FileState(\.userProfile) var userProfile: UserProfile @FileState(\.largeDataset) var largeDataset: [String] var body: some View { VStack { Text("Name: \(userProfile.name), Age: \(userProfile.age)") Button("Update Profile") { userProfile = UserProfile(name: "UpdatedName", age: 30) } List(largeDataset, id: \.self) { item in Text(item) } Button("Add Item") { largeDataset.append("Item \(largeDataset.count + 1)") } } } } ``` -------------------------------- ### Versioned Model with Custom Decoding Logic Source: https://github.com/0xleif/appstate/blob/main/documentation/en/migration-considerations.md Use a version field within your Codable model and implement custom decoding logic to handle migration of older data formats to newer ones based on the version number. ```swift struct Settings: Codable { var version: Int var text: String var isDarkMode: Bool // Handle version-specific decoding logic init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.version = try container.decode(Int.self, forKey: .version) self.text = try container.decode(String.self, forKey: .text) self.isDarkMode = try container.decode(Bool.self, forKey: .isDarkMode) // If migrating from an older version, apply necessary transformations here if version < 2 { // Migrate older data to newer format } } } ``` -------------------------------- ### FilePrivate Access for State and Dependency Source: https://github.com/0xleif/appstate/wiki/Managing-Application-Access-with-AppState Utilize `fileprivate` access level to restrict State and Dependency access solely within the defining Swift file, enhancing encapsulation. ```swift fileprivate extension Application { var fileprivateStateValue: State { state(initial: 0) } var fileprivateDependencyValue: Dependency { dependency(SomeType()) } } ``` -------------------------------- ### Define FileState for Large Datasets Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-filestate.md Define a FileState to store a large array of strings, suitable for caching or offline data. Access and display the data in a SwiftUI List. ```swift import AppState import SwiftUI extension Application { @MainActor var largeDataset: FileState<[String]> { fileState(initial: [], filename: "largeDataset") } } struct LargeDataView: View { @FileState(\.largeDataset) var largeDataset: [String] var body: some View { List(largeDataset, id: \.self) { item in Text(item) } } } ``` -------------------------------- ### Task Row View for Individual Tasks Source: https://github.com/0xleif/appstate/wiki/EXAMPLE:-ToDo-List-App-with-AppState Represents a single task in the list, allowing editing of the task name and toggling its completion status via a CheckBox. ```swift struct TaskRowView: View { @Binding var task: Task var body: some View { HStack { TextField("Task name", text: $task.name) CheckBox(isChecked: $task.isCompleted) } } } ``` -------------------------------- ### Storing and Accessing a Secure Token Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-securestate.md Define a SecureState property for user tokens and use it within a SwiftUI view to store and display the token. Handle the case where the token might be nil. ```swift import AppState import SwiftUI extension Application { var userToken: SecureState { secureState(id: "userToken") } } struct SecureView: View { @SecureState(\.userToken) var userToken: String? var body: some View { VStack { if let token = userToken { Text("User token: \(token)") } else { Text("No token found.") } Button("Set Token") { userToken = "secure_token_value" } } } } ``` -------------------------------- ### Test ObservedDependency Interaction Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-observeddependency.md A test case demonstrating the interaction with ObservedDependency, verifying that changes to the observable service's properties are reflected. ```swift import XCTest @testable import AppState @MainActor fileprivate class ObservableService: ObservableObject { @Published var count: Int init() { count = 0 } } fileprivate extension Application { @MainActor var observableService: Dependency { dependency(ObservableService()) } } @MainActor fileprivate struct ExampleDependencyWrapper { @ObservedDependency(\.observableService) var service func test() { service.count += 1 } } final class ObservedDependencyTests: XCTestCase { @MainActor func testDependency() async { let example = ExampleDependencyWrapper() XCTAssertEqual(example.service.count, 0) example.test() XCTAssertEqual(example.service.count, 1) } } ``` -------------------------------- ### Use Generated Unique IDs for States and Dependencies Source: https://github.com/0xleif/appstate/wiki/Managing-Application-Access-with-AppState When no ID is provided, AppState generates a unique ID based on the definition location, offering a preferred method for unique identification and protection. ```swift extension Application { var defaultValue: State { state(initial: 0) // The ID will be generated by AppState } var defaultDependency: Dependency { dependency(initial: SomeType()) // The ID will be generated by AppState } } ``` -------------------------------- ### Access Specific Parts of State with Slice Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-overview.md Employ @Slice and @OptionalSlice to access specific parts of your application's state. This allows for targeted updates and access to nested properties. ```swift import AppState import SwiftUI struct SlicingView: View { @Slice(\.user, \.name) var name: String var body: some View { VStack { Text("Username: \(name)") Button("Update Username") { name = "NewUsername" } } } } ``` -------------------------------- ### Use @AppState for In-Memory State Source: https://context7.com/0xleif/appstate/llms.txt Bind SwiftUI views to global in-memory state defined on Application. Changes are propagated reactively to all observing views. ```swift import AppState import SwiftUI struct User { var name: String var isLoggedIn: Bool } extension Application { var user: State { state(initial: User(name: "Guest", isLoggedIn: false)) } } struct ContentView: View { @AppState(\.user) var user: User var body: some View { VStack { Text("Hello, \(user.name)!") Button("Log in") { user.name = "John Doe" user.isLoggedIn = true } Button("Log out") { user = User(name: "Guest", isLoggedIn: false) } } } } ``` -------------------------------- ### Handle External iCloud Changes Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-syncstate.md Override didChangeExternally in a custom Application subclass to respond to changes made on other devices. Ensure UI updates are sent on the main thread. ```swift class CustomApplication: Application { override func didChangeExternally(notification: Notification) { super.didChangeExternally(notification: notification) DispatchQueue.main.async { self.objectWillChange.send() } } } ``` -------------------------------- ### Define StoredState Property Source: https://github.com/0xleif/appstate/blob/main/documentation/en/usage-storedstate.md Declare a StoredState property by extending the Application object. This sets up a persistent state variable with an initial value and a unique identifier. ```swift import AppState extension Application { var userPreferences: StoredState { storedState(initial: "Default Preferences", id: "userPreferences") } } ```