AppStorage
is the easiest way to access UserDefaults
in SwiftUI. It works like State
and automatically retrieves and updates the underlying UserDefaults
data. It is used as such:
struct ContentView: View {
@AppStorage("SHOW_SPLASH_SCREEN") var showSplashScreen = true
var body: some View {
// content
.sheet(isPresented: $showSplashScreen) {
// splash screen
}
}
}
Here, the "SHOW_SPLASH_SCREEN"
is the key and true
is the initial value.
However, AppStorage
has two main caveats. For every usage of the same key/value, you have to make sure to always use the same key and initial value. This makes it tedious when changing either one.
The Solution
We can extend AppStorage
to use key path syntax, similar to how EnvironmentKey
s work:
@Environment(\.dismiss) var dismiss
This way, we do not have to manually type the key, but use a predefined variable. And, we do not set the initial value at call site, making it easy to change.
First, we have to create a structure that stores the keys and values:
struct KeyValuePair<Value> {
var key: String
var value: Value
init(_ key: String, value: Value) {…