Image generated with ChatGPT

Member-only story

AppSorage in SwiftUI (Form episode II°)

Nicola De Filippo
2 min readApr 10, 2024

In this post, we’ll explore how to use AppStorage. Commonly, UserDefaults is employed to save small amounts of data, such as user preferences in an app. However, it comes with certain limitations:

  • The data is saved in a single .plist file, indicating that having a large file is not the optimal solution. On Apple TV, there is a fixed limit of 1 MB, but it’s recommended to keep the file size smaller, particularly if these default values are loaded at app startup for speed considerations.
  • The data is stored in plaintext, so it’s NOT suitable for sensitive information.
  • The permitted types are: Data, String, Date, Bool, Int, Double, Float, Array, Dictionary, and URL.

What is AppStorage? It’s a wrapper for UserDefaults that allows us to save and load data from UserDefaults without having to directly call it.

Take a look at a short example:

struct ContentView: View {
@AppStorage("enabled") private var enabled = false
@AppStorage("nickname") private var nickname = ""

var body: some View {
VStack {
Form {
TextField("Nickname", text: $nickname)
Toggle(isOn: $enabled) {
Text("Enable")
}
}
}
.padding()
}
}

So, we declare the variable with @AppStorage and use it similarly to how we use @State variables. The primary difference is that, in this case, the changes are automatically saved (and loaded).

Simple and powerful. That’all.

(originally posted here https://nicoladefilippo.com/appsorage-in-swiftui-form-episode-ii/)

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Nicola De Filippo
Nicola De Filippo

Written by Nicola De Filippo

Software Engineer and Entrepreneur

No responses yet

Write a response