Using @AppStorage to Access UserDefaults in SwiftUI
In the past, developers often use UserDefaults to store small amount of data such as user preferences or settings. Starting with iOS 14, Apple introduced the @AppStorage property wrapper in SwiftUI. Through @AppStorage, developer can store value in UserDefaults in a more seamless and easier way.
Here is an example of how @AppStorage is used.
import SwiftUI
struct ContentView: View {
@AppStorage("isPlayMode") var isPlayMode: Bool = false
var body: some View {
VStack {
Toggle("Enable Play Mode", isOn: $isPlayMode)
Text("Play Mode is \(isPlayMode ? "Enabled" : "Disabled")")
}
}
}
In this example, we bind a Bool value in UserDefaults with the key “isPlayMode”. When we access or modify isPlayMode, it reads from or writes to UserDefaults using this key.
Notice that @AppStorage is a wrapper around UserDefaults, therefore the supported types are the same as those supported by UserDefaults. For more details, refer to the API documentation for UserDefaults.
@AppStorage is a welcomed addition to SwiftUI. By simplifying the process of synchronizing with UserDefaults, it allows developers to write code that are easier to read.