SwiftUI: What is @AppStorage property wrapper

前端 未结 5 2009
攒了一身酷
攒了一身酷 2020-12-19 03:34

I used to save important App data like login credentials into UserDefaults using the following statement:

UserDefaults.standard.set("sample@email.com&quo         


        
5条回答
  •  南笙
    南笙 (楼主)
    2020-12-19 04:11

    @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:

    • What is the @AppStorage property wrapper?
    • AppStorage Property Wrapper SwiftUI

提交回复
热议问题