### Install SwiftHelpers Package Source: https://context7.com/stalkermv/swifthelpers/llms.txt Instructions for adding SwiftHelpers to your Swift package dependencies and importing its modules into your targets. This includes the main module, SwiftStorage, and Development. ```swift // Package.swift dependencies: [ .package(url: "https://github.com/stalkermv/SwiftHelpers", from: "1.0.0") ] // Target dependencies .target(name: "YourTarget", dependencies: [ "SwiftHelpers", // Main module (includes FoundationExtensions + CombineExtensions) "SwiftStorage", // Secure storage functionality "Development" // Development utilities ]) ``` -------------------------------- ### Type-Safe Secure Storage Keys with SecureStorageKey Protocol Source: https://context7.com/stalkermv/swifthelpers/llms.txt Illustrates the definition of type-safe storage keys using the SecureStorageKey protocol. This allows for associated value types and default values, enhancing type safety when interacting with secure storage. Includes an example of using these keys within a SwiftUI view. ```swift import SwiftStorage import SwiftUI // Define typed storage keys enum AuthToken: SecureStorageKey { typealias Value = String static var defaultValue: String = "" } enum UserCredentials: SecureStorageKey { typealias Value = String? // Optional types auto-default to nil } struct SecureView: View { @SecureStorage(AuthToken.self) var token: String @SecureStorage(UserCredentials.self) var credentials: String? var body: some View { VStack { Text("Authenticated: (!token.isEmpty)") Button("Set Token") { token = "secure_(Date().timeIntervalSince1970)" } } } } ``` -------------------------------- ### Debug SwiftUI Bindings with Logging in Swift Source: https://context7.com/stalkermv/swifthelpers/llms.txt The Development module offers a convenient way to debug SwiftUI bindings by logging their get and set operations to the console. You can customize the prefix and format of the logged output for better clarity during development. ```swift import Development import SwiftUI struct DebugView: View { @State private var count = 0 @State private var name = "Alice" var body: some View { VStack { // Print binding access with prefix Stepper("Count", value: $count.print("Counter")) // Console output: // {< GET} Counter: 0 // {> SET} Counter: 1 // Custom formatting TextField("Name", text: $name.print("Name") { value in "'\(value)' (length: \(value.count))" }) // Console output: // {< GET} Name: 'Alice' (length: 5) // {> SET} Name: 'Alice B' (length: 7) } } } ``` -------------------------------- ### Secure Storage Service Implementations and Usage Source: https://context7.com/stalkermv/swifthelpers/llms.txt Details the SecureStorageService protocol and its implementations like KeychainSecureStorage and InMemorySecureStorage. Shows how to use different storage backends and provides utility functions for saving, loading, and observing data changes through the storage services. ```swift import SwiftStorage // KeychainSecureStorage - Production use (default) let keychainStorage = KeychainSecureStorage.shared // InMemorySecureStorage - Testing and ephemeral storage let memoryStorage = InMemorySecureStorage.shared // Use custom storage in SecureStorage struct TestableView: View { @SecureStorage("key", defaultValue: "default", store: InMemorySecureStorage.shared) var testValue: String var body: some View { Text(testValue) } } // Direct storage service usage func saveSecurely(_ value: T, key: String, storage: SecureStorageService) throws { try storage.set(value, forKey: key) } func loadSecurely(key: String, storage: SecureStorageService) throws -> T { try storage.value(type: T.self, forKey: key) } // Observe storage changes func observeChanges(key: String, storage: SecureStorageService) async throws { for try await value: T in storage.observe(key: key) { print("Value changed: (value)") } } ``` -------------------------------- ### Bundle Version Information Access (Swift) Source: https://context7.com/stalkermv/swifthelpers/llms.txt Access application version, build number, and environment information directly from the app's bundle in Swift. Provides properties for version string, build number, combined version, production environment check, and receipt URL. Requires the FoundationExtensions library. ```swift import FoundationExtensions // Version string (CFBundleShortVersionString) let versionString = Bundle.main.appVersionString // "1.2.3" // Build number (CFBundleVersion) let buildNumber = Bundle.main.buildNumber // 42 // Combined version with build let fullVersion = Bundle.main.appVersionWithBuildNumber // "1.2.3 (42)" // Check production environment if Bundle.main.isProduction { // Production-only code (analytics, crash reporting, etc.) } // Receipt URL for in-app purchase validation if let receiptURL = Bundle.main.appStoreProductionReceiptURL { // Validate receipt at receiptURL } ``` -------------------------------- ### Development Utilities: Lorem Ipsum and Debug Printing Source: https://github.com/stalkermv/swifthelpers/blob/main/README.md This snippet showcases development utilities provided by the `Development` library. It includes functions for generating random sentences, paragraphs, and Lorem ipsum text, as well as creating random image URLs. Additionally, it demonstrates debug binding printing for `@State` variables in SwiftUI. ```swift import Development // Lorem ipsum generation let sentence = String.randomSentence() let paragraph = String.randomParagraph() let lorem = String.randomLorem() // Random image URLs let imageURL = URL.randomImage(width: 300, height: 200) // Debug binding printing @State private var count = 0 var body: some View { Stepper("Count", value: $count.print("Counter")) } // Console output: // {< GET} Counter: 0 // {> SET} Counter: 1 ``` -------------------------------- ### Development Utilities for Swift Source: https://github.com/stalkermv/swifthelpers/blob/main/README.md Offers various extensions for development and debugging purposes in Swift. This includes string extensions for generating Lorem ipsum text, URL extensions for random image generation, and view extensions for enforcing software keyboard appearance. ```swift import Development // Example usage of Lorem ipsum generation: let loremText = String.loremIpsum() // Example usage of random image URL generation: let randomImageURL = URL.randomImageURL(width: 300, height: 200) // Example usage of binding debug printing: // @State var myValue: Int = 0 // Text("Value: \(myValue)").debugPrint("MyValueBinding") // Example usage of software keyboard enforcement: // SomeView().enforceKeyboard() ``` -------------------------------- ### Type-Safe AppStorage Keys and Combine Publishers Source: https://context7.com/stalkermv/swifthelpers/llms.txt Explains how to enhance SwiftUI's AppStorage with type-safe keys using the AppStorageKey protocol. It also demonstrates observing UserDefaults changes using Combine publishers, providing a reactive way to manage application settings. ```swift import SwiftStorage import SwiftUI import Combine // Define typed AppStorage keys enum DarkModeEnabled: AppStorageKey { typealias Value = Bool static var defaultValue: Bool = false } enum FontSize: AppStorageKey { typealias Value = Int static var defaultValue: Int = 14 } enum LastSyncDate: AppStorageKey { typealias Value = Date? // Optional auto-defaults to nil } struct SettingsView: View { @AppStorage(DarkModeEnabled.self) var isDarkMode: Bool @AppStorage(FontSize.self) var fontSize: Int var body: some View { Form { Toggle("Dark Mode", isOn: $isDarkMode) Stepper("Font Size: (fontSize)", value: $fontSize, in: 10...24) } } } // Observe UserDefaults changes with Combine class SettingsObserver { var cancellables = Set() func observeSettings() { UserDefaults.standard.publisher(for: DarkModeEnabled.self) .sink { print("Dark mode changed: ($0)") } .store(in: &cancellables) } } ``` -------------------------------- ### Semantic Version Number Parsing and Comparison (Swift) Source: https://context7.com/stalkermv/swifthelpers/llms.txt Handle semantic version numbers (MAJOR.MINOR.PATCH) in Swift. Includes parsing from strings, creation from components, comparison operators, retrieving app version from the bundle, and asynchronously checking the App Store version. Requires the SwiftHelpers library. ```swift import SwiftHelpers // Parse from string let version = SemanticVersionNumber(version: "2.1.3") print(version?.major) // 2 print(version?.minor) // 1 print(version?.patch) // 3 // Create from components let v1 = SemanticVersionNumber(major: 1, minor: 0, patch: 0) let v2 = SemanticVersionNumber(major: 2, minor: 0, patch: 0) // Compare versions if v1 < v2 { print("Update available") // Prints: Update available } // Get app version let appVersion = Bundle.main.appVersion // SemanticVersionNumber from Info.plist // Check App Store version (async) Task { if let storeVersion = try await Bundle.main.currentAppStoreVersion { if Bundle.main.appVersion < storeVersion { print("New version \(storeVersion) available!") } } } // String representation print(v1.description) // "1.0.0" ``` -------------------------------- ### Generate Placeholder Text with Development Module in Swift Source: https://context7.com/stalkermv/swifthelpers/llms.txt The Development module provides utilities for generating random placeholder text, including words, sentences, paragraphs, and full Lorem Ipsum content. It also supports generating random alphanumeric strings of a specified length. These are useful for UI previews and prototyping. ```swift import Development // Random word let word = String.randomWord() // e.g., "lorem" // Random sentence (5-15 words, capitalized) let sentence = String.randomSentence() // e.g., "Lorem ipsum dolor sit amet consectetur" // Random paragraph (3-7 sentences) let paragraph = String.randomParagraph() // Random multi-paragraph text let lorem = String.randomLorem() // 3-7 paragraphs // Controlled generation let fiveWords = String.randomLorem(words: 5) let threeSentences = String.randomLorem(sentences: 3) let twoParagraphs = String.randomLorem(paragraphs: 2) // Random alphanumeric string let randomString = String.random(length: 16) // e.g., "aB3xK9mNpQ2wR7yZ" ``` -------------------------------- ### SwiftUI Secure Storage with Property Wrappers Source: https://github.com/stalkermv/swifthelpers/blob/main/README.md Enables secure data storage in SwiftUI applications using property wrappers. It supports automatic observation for reactive updates and offers different storage implementations like Keychain, in-memory, and disk-based storage. ```swift import SwiftStorage import SwiftUI // Basic secure storage with automatic observation struct ContentView: View { @SecureStorage("user_preference", defaultValue: "default") var userPreference: String var body: some View { VStack { Text("Current preference: \(userPreference)") Button("Update Preference") { userPreference = "updated_\(Date().timeIntervalSince1970)" } if let error = _userPreference.error { Text("Error: \(error.localizedDescription)") } } } } // Type-safe storage with keys enum UserSettings: SecureStorageKey { typealias Value = String static var defaultValue: String = "default" } struct SettingsView: View { @SecureStorage(UserSettings.self) var userSetting: String var body: some View { Text("Setting: \(userSetting)") } } // Custom storage service struct ContentView: View { @SecureStorage("key", defaultValue: "default", store: InMemorySecureStorage.shared) var value: String var body: some View { Text(value) } } ``` -------------------------------- ### Secure Storage Property Wrapper in SwiftUI Source: https://context7.com/stalkermv/swifthelpers/llms.txt Demonstrates how to use the @SecureStorage property wrapper to securely store sensitive data in the keychain with SwiftUI integration. It supports default values and optional types, and includes basic error handling for storage operations. ```swift import SwiftStorage import SwiftUI struct ContentView: View { // Basic secure storage with default value @SecureStorage("auth_token", defaultValue: "") var authToken: String // Optional secure storage (nil default) @SecureStorage("user_id") var userId: String? var body: some View { VStack { Text("Token: (authToken.prefix(10))...") Button("Login") { authToken = "new_secure_token_(UUID().uuidString)" } Button("Logout") { authToken = "" userId = nil } // Error handling if let error = _authToken.error { Text("Storage error: (error.localizedDescription)") .foregroundColor(.red) } } } } ``` -------------------------------- ### Optional Safe Unwrapping with Error Context (Swift) Source: https://context7.com/stalkermv/swifthelpers/llms.txt Safely unwrap optional values in Swift, providing detailed error information including file and line context. Supports basic unwrapping, custom errors, and custom error messages. Requires the FoundationExtensions library. ```swift import FoundationExtensions let optionalValue: String? = nil let validValue: String? = "Hello" // Basic unwrap with automatic error context do { let value = try optionalValue.unwrapped() } catch { print(error.localizedDescription) // "Received an unexpected empty value" } // Unwrap with custom error enum MyError: Error { case missingData } do { let value = try optionalValue.unwrapped(or: MyError.missingData) } catch MyError.missingData { print("Data was missing") } // Unwrap with custom message do { let value = try optionalValue.unwrapped("User name is required") } catch { print(error.localizedDescription) // "User name is required" } // Successful unwrap let greeting = try validValue.unwrapped() // "Hello" ``` -------------------------------- ### Date Extensions for Manipulation and Comparison (Swift) Source: https://context7.com/stalkermv/swifthelpers/llms.txt Enhance the Date type in Swift with convenient properties and methods for common date operations. Includes navigation between days, day/month boundaries, date component access, time manipulation, and date comparisons. Requires the FoundationExtensions library. ```swift import FoundationExtensions let today = Date() // Navigate between days let yesterday = today.yesterday let tomorrow = today.tomorrow // Day boundaries let dayStart = today.startOfDay let dayEnd = today.endOfDay // Month operations let monthStart = today.startOfMonth let monthEnd = today.endOfMonth let isLastDay = today.isLastDayOfMonth // Date components let dayNumber = today.day // e.g., 15 let monthNumber = today.month // e.g., 6 let noonTime = today.noon // Add time components let nextWeek = today.add(.days(7)) let inTwoHours = today.add(.hours(2)) let futureDate = today.add(.months(1), .days(15), .hours(3)) // Compare dates let daysDifference = today.daysDiff(from: yesterday) // 1 let isSameDay = today.isDayEquals(Date()) // true // Set time from another date let appointmentTime = Calendar.current.date(bySettingHour: 14, minute: 30, second: 0, of: today)! let tomorrowSameTime = tomorrow.setTime(from: appointmentTime) // Parse ISO 8601 let isoDate = try Date.iso8601(string: "2024-01-15T10:30:00.000Z") ``` -------------------------------- ### Foundation Extensions for Swift Source: https://github.com/stalkermv/swifthelpers/blob/main/README.md Provides extensions for Swift's Foundation framework, including safe array subscripting, sorting by key path, value clamping, and robust optional unwrapping with error handling. It also offers unique filtering for sequences. ```swift import FoundationExtensions // Safe array subscripting let numbers = [1, 2, 3, 4, 5] let safeValue = numbers[safeIndex: 10] // Returns nil instead of crashing // Array sorting by key path struct Person { let name: String let age: Int } let people = [Person(name: "Alice", age: 30), Person(name: "Bob", age: 25)] let sortedByName = people.sorted(keyPath: \.name) let sortedByAge = people.sorted(keyPath: \.age, ascending: false) // Value clamping let clampedValue = 15.clamped(to: 10...20) // Returns 15 let clampedHigh = 25.clamped(to: 10...20) // Returns 20 // Safe optional unwrapping with detailed errors let optionalValue: String? = nil do { let value = try optionalValue.unwrapped() } catch { print("Failed to unwrap: \(error)") } // Unique filtering let numbers = [1, 2, 2, 3, 3, 3, 4] let uniqueNumbers = numbers.unique() // [1, 2, 3, 4] let uniqueByProperty = people.unique(by: \.age) ``` -------------------------------- ### Find First Array Index by KeyPath in Swift Source: https://context7.com/stalkermv/swifthelpers/llms.txt Locate the first index of an element in an array by comparing a specific property using a KeyPath. This is useful for searching based on unique identifiers or other properties. ```swift import FoundationExtensions struct User { let id: Int let name: String } let users = [ User(id: 1, name: "Alice"), User(id: 2, name: "Bob"), User(id: 3, name: "Charlie") ] // Find index by matching a property let targetUser = User(id: 2, name: "Robert") // Different name, same id if let index = users.firstIndex(of: targetUser, by: \.id) { print("Found at index \(index)") // Found at index 1 } ``` -------------------------------- ### Combine Extensions: Bridge Async/Await with Combine Source: https://github.com/stalkermv/swifthelpers/blob/main/README.md This snippet demonstrates how to bridge Swift's async/await functionality with the Combine framework using `TaskFuture`. It shows how to create a `TaskFuture` from an async task and then use the `.sink` method to receive completion events and values. ```swift import CombineExtensions import Combine // Bridge async/await with Combine let future = TaskFuture { try await Task.sleep(nanoseconds: 1_000_000_000) return 42 } future .sink( receiveCompletion: { completion in switch completion { case .finished: print("Completed successfully") case .failure(let error): print("Failed with error: (error)") } }, receiveValue: { value in print("Received value: (value)") } ) ``` -------------------------------- ### Combine Extensions for Async/Await Bridging Source: https://github.com/stalkermv/swifthelpers/blob/main/README.md Provides utilities for the Combine framework, specifically a TaskFuture for bridging asynchronous operations (async/await) with Combine publishers. This allows seamless integration of modern Swift concurrency with reactive streams. ```swift import CombineExtensions // Example usage of TaskFuture would go here, demonstrating bridging async/await with Combine. ``` -------------------------------- ### Generate Random Image URLs with Development Module in Swift Source: https://context7.com/stalkermv/swifthelpers/llms.txt This utility generates random placeholder image URLs using picsum.photos. You can specify dimensions (width and height) and a seed for consistent image generation. These URLs are ideal for use in previews and prototyping within SwiftUI applications. ```swift import Development import SwiftUI // Default 200x300 image with random seed let imageURL = URL.randomImage() // Custom dimensions let squareImage = URL.randomImage(width: 300, height: 300) let bannerImage = URL.randomImage(width: 800, height: 200) // Specific seed for consistent image let consistentImage = URL.randomImage(seed: "42", width: 400, height: 400) // Use in SwiftUI previews struct ImagePreview: View { var body: some View { AsyncImage(url: URL.randomImage(width: 300, height: 200)) { image in image.resizable().aspectRatio(contentMode: .fit) } placeholder: { ProgressView() } } } ``` -------------------------------- ### TaskFuture: Bridge Async/Await with Combine Publishers in Swift Source: https://context7.com/stalkermv/swifthelpers/llms.txt TaskFuture allows seamless integration of Swift's async/await functionality with Combine publishers. It enables the creation of Combine publishers from async closures and can be used with existing async functions. This is particularly useful for gradually migrating Combine-based codebases to Swift concurrency. ```swift import CombineExtensions import Combine var cancellables = Set() // Create from async closure let future = TaskFuture { try await Task.sleep(nanoseconds: 1_000_000_000) return 42 } future .sink( receiveCompletion: { completion in switch completion { case .finished: print("Completed successfully") case .failure(let error): print("Failed: (error)") } }, receiveValue: { value in print("Received: (value)") // Received: 42 } ) .store(in: &cancellables) // Use with async functions func fetchUser(id: Int) async throws -> String { try await Task.sleep(nanoseconds: 500_000_000) return "User (id)" } let userFuture = TaskFuture { try await fetchUser(id: 123) } userFuture .map { "Hello, \($0)!" } .sink( receiveCompletion: { _ in }, receiveValue: { greeting in print(greeting) // Hello, User 123! } ) .store(in: &cancellables) ``` -------------------------------- ### Array Sorting by KeyPath in Swift Source: https://context7.com/stalkermv/swifthelpers/llms.txt Sort arrays based on a comparable property specified by a KeyPath. Supports ascending and descending order, and handles optional properties gracefully by placing nil values at the end. ```swift import FoundationExtensions struct Person { let name: String let age: Int let nickname: String? } let people = [ Person(name: "Alice", age: 30, nickname: "Ali"), Person(name: "Bob", age: 25, nickname: nil), Person(name: "Charlie", age: 35, nickname: "Chuck") ] // Sort by non-optional property let sortedByName = people.sorted(keyPath: \.name) // Alice, Bob, Charlie let sortedByAgeDesc = people.sorted(keyPath: \.age, ascending: false) // Charlie, Alice, Bob // Sort by optional property (nil values appear at end) let sortedByNickname = people.sorted(keyPath: \.nickname) // Ali, Chuck, nil ``` -------------------------------- ### Array Mutation and Functional Append in Swift Source: https://context7.com/stalkermv/swifthelpers/llms.txt Perform in-place mutations on array elements non-destructively, returning a new array with the modified elements. Also includes a functional method to append elements, creating a new extended array. ```swift import FoundationExtensions let numbers = [1, 2, 3, 4, 5] // Mutate elements (non-destructive, returns new array) let doubled = numbers.mutate { $0 *= 2 } print(doubled) // [2, 4, 6, 8, 10] print(numbers) // [1, 2, 3, 4, 5] (original unchanged) // Functional append let extended = numbers.appending(6) // [1, 2, 3, 4, 5, 6] ``` -------------------------------- ### Value Clamping to Range in Swift Source: https://context7.com/stalkermv/swifthelpers/llms.txt Constrain any Comparable value to a specified closed range. Ensures that a value stays within the defined minimum and maximum bounds, useful for UI inputs and calculations. ```swift import FoundationExtensions // Clamp integers let value = 15.clamped(to: 10...20) // 15 let tooLow = 5.clamped(to: 10...20) // 10 let tooHigh = 25.clamped(to: 10...20) // 20 // Clamp doubles let percentage = 1.5.clamped(to: 0.0...1.0) // 1.0 // Clamp in UI contexts let opacity = userInput.clamped(to: 0.0...1.0) let volume = sliderValue.clamped(to: 0...100) ``` -------------------------------- ### Sequence Unique Filtering in Swift Source: https://context7.com/stalkermv/swifthelpers/llms.txt Filter sequences to remove duplicate elements while preserving their original order. Supports uniqueness based on the element itself (for Hashable types) or a custom property via a KeyPath or closure. ```swift import FoundationExtensions // Unique for Hashable elements let numbers = [1, 2, 2, 3, 3, 3, 4, 1] let uniqueNumbers = numbers.unique() // [1, 2, 3, 4] // Unique by custom property struct Item { let id: Int let category: String } let items = [ Item(id: 1, category: "A"), Item(id: 2, category: "A"), Item(id: 3, category: "B") ] let uniqueByCategory = items.unique(by: \.category) // Items with id 1 and 3 let uniqueById = items.unique { $0.id } // All three items ``` -------------------------------- ### Safe Array Subscripting in Swift Source: https://context7.com/stalkermv/swifthelpers/llms.txt Safely access array elements using a custom subscript that returns nil for out-of-bounds indices or a default value when provided. This prevents runtime crashes due to invalid index access. ```swift import FoundationExtensions let numbers = [1, 2, 3, 4, 5] // Safe subscript returns nil for out-of-bounds let value = numbers[safeIndex: 10] // nil let validValue = numbers[safeIndex: 2] // Optional(3) // Default value subscript let withDefault = numbers[10, default: 0] // 0 let existing = numbers[2, default: 0] // 3 ``` -------------------------------- ### Conditional Assignment Operator for Optionals (Swift) Source: https://context7.com/stalkermv/swifthelpers/llms.txt Assign values conditionally using the '?=' operator in Swift. This operator assigns the right-hand side value to the left-hand side only if the right-hand side is non-nil. It works for optional-to-optional and optional-to-non-optional assignments. Requires the SwiftHelpers library. ```swift import SwiftHelpers // Optional to optional assignment var name: String? = "Alice" let newName: String? = "Bob" name ?= newName // name is now "Bob" let emptyName: String? = nil name ?= emptyName // name remains "Bob" // Optional to non-optional assignment var count = 5 let newCount: Int? = 10 count ?= newCount // count is now 10 let noUpdate: Int? = nil count ?= noUpdate // count remains 10 // Useful for partial updates struct Settings { var theme: String var fontSize: Int } var settings = Settings(theme: "dark", fontSize: 14) let themeUpdate: String? = "light" let fontUpdate: Int? = nil settings.theme ?= themeUpdate // theme is now "light" settings.fontSize ?= fontUpdate // fontSize remains 14 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.