I used to save important App data like login credentials into UserDefaults using the following statement:
UserDefaults.standard.set("sample@email.com&quo
This is a persistent storage provided by SwiftUI. This code will persist the email across app launches.
struct AppStorageView: View {
@AppStorage("emailAddress") var emailAddress = "initial@hey.com"
var body: some View {
TextField("Email Address", text: $emailAddress)
}
}
With pure SwiftUI code, we can now persist such data without using UserDefaults
at all.
But if you do want to access the underlying data, it is no secret that the wrapper is using UserDefaults
. For example, you can still update using UserDefaults.standard.set(...)
, and the benefit is that AppStorage observes the store, and the SwiftUI view will update automatically.