AppSorage in SwiftUI (Form episode II°)

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.

share this post with friends

Picture of Nicola De filippo

Nicola De filippo

I'm a software engineer who adds to the passion for technologies the wisdom and the experience without losing the wonder for the world. I love to create new projects and to help people and teams to improve

Leave a comment

Your email address will not be published. Required fields are marked *

Who I am

I'm a software engineer who adds to the passion for technologies the wisdom and the experience without losing the wonder for the world. I love to create new projects and to help people and teams to improve.

Follow Me Here

Get The Latest Updates

Periodically receive my super contents on coding and programming

join the family;)

Recent Posts