Skip to content
DeveloperMemos

Using SwiftUI's @AppStorage

SwiftUI, Data storage, Property wrapper2 min read

When it comes to data storage in iOS apps, there are many options to choose from. One of the most common ways to store data is by using UserDefaults. UserDefaults is a key-value storage mechanism that allows you to store simple data types such as strings, numbers, and booleans. However, UserDefaults has some limitations when it comes to data types, and managing UserDefaults can become cumbersome when you have many keys to manage. In this post, we will learn how to use SwiftUI's @AppStorage property wrapper, which provides a simpler and more elegant way to store and retrieve small amounts of data across app launches.

What is @AppStorage?

@AppStorage is a new property wrapper introduced in SwiftUI 2.0. It allows you to store and retrieve simple data types across app launches. @AppStorage uses UserDefaults under the hood, but it abstracts away the complexity of managing UserDefaults by providing a simple and concise API.

How to use @AppStorage

Using @AppStorage is very simple. First, you need to declare a property with the @AppStorage property wrapper. Here's an example:

1@AppStorage("isLoggedIn") var isLoggedIn = false

In this example, we declare a boolean property called isLoggedIn and mark it with the @AppStorage property wrapper. The first argument of @AppStorage is the key that will be used to store and retrieve the value of the property. In this case, the key is "isLoggedIn".

Once you've declared your @AppStorage property, you can use it just like any other property. For example, you can bind it to a Toggle view like this:

1Toggle("Logged in", isOn: $isLoggedIn)

In this example, we bind the value of the isLoggedIn property to the isOn parameter of the Toggle view. This means that the Toggle view will reflect the current value of isLoggedIn and update it when the user toggles the switch.

You can also use @AppStorage to store other types of data, such as strings and integers. Here's an example:

1@AppStorage("name") var name = "John Doe"

In this example, we declare a string property called name and mark it with the @AppStorage property wrapper. The key for this property is "name". By default, the value of name is "John Doe", but you can change it like this:

1name = "Jane Doe"

Wrap Up

@AppStorage is a simple and elegant way to store and retrieve small amounts of data across app launches. It abstracts away the complexity of managing UserDefaults and provides a concise API that makes it easy to work with. If you're building an iOS app with SwiftUI, you should definitely consider using @AppStorage for your data storage needs.