70 %
Chris Biscardi

The SwiftUI @AppStorage property wrapper

@AppStorage is:

A property wrapper type that reflects a value from UserDefaults and invalidates a view on a change in value in that user default.

So basically that means that by annotating our property with the @AppStorage wrapper, we basically get a React.useState where the data is stored in the application storage instead of in memory. Specifically this place is called UserDefaults.

(UserDefaults is...) An interface to the user’s defaults database, where you store key-value pairs persistently across launches of your app.

Consider the following example that stores a "colorMode" key. We can change the value using a Button action, and the value gets stored for us.

swift
struct ContentView: View {
@AppStorage("colorMode")
var colorMode = "light"
var body: some View {
Button(action: {
colorMode = colorMode == "light" ? "dark" : "light"
}, label: {
Text("Button")
})
.padding()
.foregroundColor(colorMode == "light" ? .blue : .red)
}
}

Depending on the value in UserDefaults, our button will render with either blue or red text. This value will persist across application restarts with no additional code other than the example shown here.