UserDefaults In SwiftUI

The second version of SwiftUI and iOS14 introduced a new way to edit UserDefaults. It’s a property wrapper called AppStorage.

It works in the way that you create a property wrapper with some key. This key is represented in UserDefaults. When you assign some value during creation then it’s the default value.

Let’s create one.

@AppStorage(“ButtonTapsCount”) private var tapsCount = 0

ButtonTapsCount is key. tapsCount is a local name to use it and 0 is a default value.

When you want to edit it, you just need to change the tapsCount value and it refreshes automatically. Changing that value invalidates view.

Create Text to show the current value and Button to increate tapsCount.

VStack {
Text(“Taps count: \(tapsCount))
Button(“Tap me!”) {
    tapsCount += 1

When you refresh the app the value will remain. To test it you can change the key to something else, for example from ButtonTapsCount to ButtonTapsCount2 and value tapsCount will have value 0.

@AppStorage(“ButtonTapsCount2”) private var tapsCount = 0

When you back to ButtonTapsCount then the previous value will back.