What is swiftui AppStorage property wrapper ?

Jan 11, 2022 swiftui

What is swiftui AppStorage property wrapper ?

As apple introduced SwiftUI it also changed the use of Userdefault storage as SwiftUI AppStorage as the property wrapper.

SwiftUI provides 2 different types of App state they are

  1. Appstorage
  2. SceneStorage

They are basically used to restore the value with change in userdefault key values . it update the view as there is chnage in userdefault.

In programming terms, we’ve all known since before SwiftUI that the UserDefaults class in the Foundation framework may be used to obtain user defaults. This is still true in today’s world. However, with the arrival of the SwiftUI framework, a new actor has emerged: the @AppStorage property wrapper.

SwiftUI provides a number of property wrappers, including @AppStorage. It can be thought of as an app-wide source of truth, but it differs from others in that updated values are written to the user defaults file rather than remaining in memory. It’s simple to use it for reading and writing values, and we’re about to go over a few ideas related to it in this piece.

@AppStorage

SwiftUI AppStorage is the property wrapper that reflect the value change in UserDefault. It is basically used to validate the view as per change in the userdefault.

Syntax for AppStorage

@frozen @propertyWrapper struct AppStorage

example:

    @AppStorage("emailid") var emailID: String = "[email protected]"

By default, @AppStorage monitors UserDefaults.standard, but you can provide a specific app group to monitor, such as this:

@AppStorage("UserID", store: UserDefaults(suiteName: "com.leadbycode.user")) var userID: Int = 21

Using the AppStorage inside the code as follows

struct AppContentView: View {
    
    @AppStorage("UserID", store: .standard) var showUserID: Bool = false
    
    var body: some View {
        VStack {
            Text(showUserID ? "21" : "")
                .padding()
            Button("Change userID") {
                showUserID.toggle()
            }
            Toggle("Change UserID", isOn: $showUserID)
        }
    }
}

When compared to the original @UserDefault property wrapper, there are two key differences:

  • The preferences container now contains the user defaults. This allows us to load a user defaults store into the preferences container and utilize it directly for each property. It is no longer necessary to define it per property.
  • The passthrough subject communicates the changed key-path to the subscript setter, allowing us to track changes for specific keys later.

Index