Using AppStorage to Store and Access User Defaults in SwiftUI

WWDC20 introduced AppStorage, a new property wrapper around UserDefaults that lets you write and read from UserDefaults more easily. Read the section about UserDefaults to learn more about it. In this section, let's learn how to set a new UserDefaults variable using AppStorage, how to read from it and how to change a variable in AppStorage.

 Use the newly introduced AppStorage to add to UserDefaults.

Set a variable in UserDefaults 

To create a new variable in UserDefaults and set its initial value, simply call the AppStorage wrapper and set your initial value directly:

@AppStorage("themePreference") var themePreference: String = "dark"

..

Read from UserDefaults 

To read the themePreference variable in UserDefaults, you just need to call the themePreference variable:

Text("Your theme preference is: \(themePreference).")

..

Write to UserDefaults 

To change a variable, simply assign it a new value:

Button("Change theme preference to light") {
		themePreference = "light"
}

..

Notes

  • In conclusion, AppStorage is a new wrapper introduced at WWDC20 and makes it easier to write and read from UserDefaults, as well as makes the code cleaner to read. 
  • Remember to not store too much data in the AppStorage and to not store sensitive information in it as it is not very secure and easily hackable.

Demo
To use AppStorage to store and access user defaults in SwiftUI:
import SwiftUI

struct ContentView: View {
    @AppStorage("username") var username = "JohnDoe"
    @AppStorage("isDarkModeOn") var isDarkModeOn = false
    
    var body: some View {
        VStack {
            Text("Username: \(username)")
                .padding()
            
            Toggle(isOn: $isDarkModeOn) {
                Text("Dark Mode")
            }
            .padding()
        }
        .preferredColorScheme(isDarkModeOn ? .dark : .light)
    }
}
In this example, we have two properties that use the @AppStorage property wrapper: username and isDarkModeOn. The first parameter of the @AppStorage property wrapper is the key that will be used to store the value in user defaults.

We can access the stored value by simply accessing the property, and we can modify it by assigning a new value to the property.

In the body of the view, we have a VStack that displays the current value of the username property using a Text view. We also have a Toggle view that toggles the value of the isDarkModeOn property.

Finally, we set the preferred color scheme of the view based on the value of the isDarkModeOn property using the preferredColorScheme modifier.
..

Comments