Introducing @AppStorage in SwiftUI

Mark van Wijnen
The Startup
Published in
7 min readSep 26, 2020

Everything you need to know about @AppStorage

What is an App?

Before we dive into @AppStorage we need to talk about what an App is first. An app is short for application, which is a software program that runs on your device, but I bet you already knew that. What you may not know is that Apple added the App-protocol to SwiftUI, which is first talked about in the App essentials in SwiftUI talk from WWDC 2020.

You have one App, that can have one or multiple Scenes that consist of one or multiple Views.

Every App has its own @AppStorage which can be accessed by all the Views in any Scene. This differs from the @SceneStorage property wrapper which has a unique storage for each of the Scenes. A View within a Scene can only access the data stored in the @SceneStorage of its own Scene and has no way of accessing the data of the @SceneStorage of another Scene. However, all Views, no matter the scenes they belong to, have access to the same data in @AppStorage.

This is how Apps, Scenes, and Views relate to one another

What is @AppStorage?

When we build our app in SwiftUI most of the data we use will be stored in the memory of our device through types as String and Integer. This doesn’t change when we use property wrappers like @State and @StateObject. However, when our app closes the memory is freed and all data we put in there is gone.

There are times when we want our data to exist across launches of our app. This might be the case for user preferences or app settings. For this purpose we use @AppStorage.

@AppStorage is a SwiftUI wrapper around UserDefaults. It helps us read and write values from and to the UserDefaults and if anything changes SwiftUI will invalidate the relevant views for us. Simply put, you can look at @AppStorage as @State which persists its data.

How to use @AppStorage?

Add the @AppStorage property wrapper to your property and give it a unique key.


Sample code:

struct RootView: View {

Mark van Wijnen
The Startup

macOS/iPadOS/iOS/watchOS/visionOS developer and SwiftUI enthousiast. “Stay Hungry, Stay Foolish!” — Steve Jobs