AppStorage in SwiftUI

DevTechie Inc
Jun 24, 2022


Photo by Vincent Botta on Unsplash

The AppStorage property wrapper was introduced with iOS 14. This property wrapper works on UserDefaults and makes it easy to store and retrieve data from UserDefaults.

UserDefaults is a permanent storage on the user’s device to store small amount of information such as welcome screen, shown flags etc.

Let’s take an example to learn usage of AppStorage with SwiftUI.

@AppStorage takes a key name string which eventually works as the key for UserDefaults to fetch and store data.

Here is what storing in UserDefault looks like:

UserDefaults.standard.set("DevTechie", forKey: "brand")
AppStorage for the same looks like this:

@AppStorage("brand") var brand: String = "DevTechie"
Retrieving from AppStorage is more seamless than UserDefaults.

Here is how fetching from UserDefaults looks like::

UserDefaults.standard.string(forKey: "brand")
Fetching from AppStorage is just like using another variable.

struct AppStorageExample: View {
    @AppStorage("brand") var brand: String = "DevTechie"
    var body: some View {
        VStack {
            Text("Brand name: \(brand)")
            TextField(brand, text: $brand)
                .textFieldStyle(.roundedBorder)
        }.padding()
    }
}
With that we have reached the end of this article. Thank you once again for reading. Subscribe to our weekly newsletter at https://www.devtechie.com