DEV Community

Thomas Prezioso Jr.
Thomas Prezioso Jr.

Posted on

@Appstorage in SwiftUI

Appstorage is a property wrapper for getting stored values from UserDefaults in SwiftUI. We use @Appstorage too reload our body view property whenever the value changes of our UserDefaults. This keeps our view up to date with the data that we have stored. Let's take a look at an example on how we can use @Appstorage in our SwiftUI project.

import SwiftUI

struct ContentView: View {
    @AppStorage("isCookieTime") var isCookieTime = false
    
    var body: some View {
            Toggle("Cookie time", isOn: $isCookieTime)
        .padding()
    }
}

In the example above we have a Toggle view for "Cookie time" 🍪. We use our @AppStorage property to watch our isCookieTime variable. If the value changes it is then stored in our UserDefaults. Now our toggle will show the stored value depending on the @AppStorage.

A example of where I use @AppStorage is for storing things like a users settings options in a settings screen of an app. I hope this helps explain how to use @AppStorage in SwiftUI.

Thanks for reading and happy coding.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay