I used to save important App data like login credentials into UserDefaults using the following statement:
UserDefaults.standard.set("sample@email.com&quo
@AppStorage is a convenient way to save and read variables from UserDefaults and use them in the same way as @State properties. It can be seen as a @State property which is automatically saved to (and read from) UserDefaults.
You can think of the following:
@AppStorage("emailAddress") var emailAddress: String = "sample@email.com"
as an equivalent of this (which is not allowed in SwiftUI and will not compile):
@State var emailAddress: String = "sample@email.com" {
get {
UserDefaults.standard.string(forKey: "emailAddress")
}
set {
UserDefaults.standard.set(newValue, forKey: "emailAddress")
}
}
Note that @AppStorage behaves like a @State: a change to its value will invalidate and redraw a View.
By default @AppStorage will use UserDefaults.standard. However, you can specify your own UserDefaults store:
@AppStorage("emailAddress", store: UserDefaults(...)) ...
Useful links: