import Foundation /// The minimal persistence seam for settings. Production uses `UserDefaults`; tests use memory. public protocol SettingsDataStoring: Sendable { /// Returns the stored data, if any. func data(forKey key: String) -> Data? /// Stores or removes data. func set(_ data: Data?, forKey key: String) } /// The production `UserDefaults` adapter. `UserDefaults` is thread-safe; the unchecked /// conformance records that no additional mutable state lives here. public final class UserDefaultsSettingsDataStore: SettingsDataStoring, @unchecked Sendable { private let defaults: UserDefaults /// Creates an adapter. public init(defaults: UserDefaults = .standard) { self.defaults = defaults } public func data(forKey key: String) -> Data? { defaults.data(forKey: key) } public func set(_ data: Data?, forKey key: String) { if let data { defaults.set(data, forKey: key) } else { defaults.removeObject(forKey: key) } } } /// Loads, caches, migrates and saves `AppSettings` as one JSON blob. /// /// `@unchecked Sendable` is safe: every cached value is guarded by `lock`, and the storage seam is /// itself Sendable. public final class SettingsStore: @unchecked Sendable { /// The single defaults key; only configuration is stored here. public static let storageKey = "com.schihei.sprachmittler.settings" private let storage: any SettingsDataStoring private let lock = NSLock() private var cached: AppSettings? /// Creates a store. public init(storage: any SettingsDataStoring = UserDefaultsSettingsDataStore()) { self.storage = storage } /// The current settings, loading and migrating once. public func current() -> AppSettings { lock.lock() defer { lock.unlock() } if let cached { return cached } let settings = loadLocked() cached = settings return settings } /// Saves settings and updates the cache. public func save(_ settings: AppSettings) throws { let data = try JSONEncoder().encode(settings) lock.lock() storage.set(data, forKey: Self.storageKey) cached = settings lock.unlock() } /// Mutates and saves atomically. public func update(_ transform: (inout AppSettings) -> Void) throws { lock.lock() defer { lock.unlock() } var settings = cached ?? loadLocked() transform(&settings) let data = try JSONEncoder().encode(settings) storage.set(data, forKey: Self.storageKey) cached = settings } /// Deletes the stored blob and returns defaults. @discardableResult public func reset() -> AppSettings { lock.lock() storage.set(nil, forKey: Self.storageKey) let settings = AppSettings() cached = settings lock.unlock() return settings } private func loadLocked() -> AppSettings { guard let data = storage.data(forKey: Self.storageKey) else { return AppSettings() } return (try? JSONDecoder().decode(AppSettings.self, from: data)) ?? AppSettings() } }