History
Loading...
Loading...
September 8, 2025
@AppStorage with custom property wrappers to create type-safe settings. Instead of manually handling UserDefaults, create @AppStorage("isDarkMode") var isDarkMode: Bool = false for automatic persistence and UI updates.Create static computed properties that return configured AppStorage instances instead of repeating key strings and default values throughout your app. This centralizes all persistence configuration in one place.
extension AppStorage {
static var userTheme: AppStorage<String> {
AppStorage(wrappedValue: "system", "user_theme_preference")
}
static var maxCacheSize: AppStorage<Int> {
AppStorage(wrappedValue: 100, "max_cache_size_mb")
}
}
struct SettingsView: View {
@AppStorage.userTheme private var theme
@AppStorage.maxCacheSize private var cacheSize
var body: some View {
Form {
Picker("Theme", selection: $theme) {
Text("System").tag("system")
Text("Dark").tag("dark")
Text("Light").tag("light")
}
Stepper("Cache: \(cacheSize)MB", value: $cacheSize, in: 50...500, step: 25)
}
}
}This approach eliminates magic strings, ensures consistent default values across views, provides compile-time safety for settings keys, and makes it easy to refactor or migrate settings later. It also prevents typos in UserDefaults keys that could cause data loss.