Search code examples
swiftswiftuiappstorage

How can I store a variable as the key of an @AppStorage variable


So I wanted to make the switch to @AppStorage in my app but I'm troubled with a specific issue.

For the key of the @AppStorage I would like to use a variable that I already have but I can not do that but I used to find a way to do it with User Defaults as the following will show.

 @State var isSignedUp = false

So I would initialise the User Defaults first as a @State var then in the .onAppear I would use the key as my id variable:

isSignedUp = UserDefaults.standard.bool(forKey: id)

What I am asking is how can I do this with @AppStorage?


Solution

  • You can separate id dependent subview and initialize AppStorage property wrapper dynamically.

    Here is a solution. Tested with Xcode 12.1 / iOS 14.1

    struct IsSignedView: View {
    
        @AppStorage var isSigned: Bool     // << declare
    
        init(id: String) {
            // Initialize with default value and dynamic key from argument
            self._isSigned = AppStorage(wrappedValue: false, id)
        }
    
        // ... other dependent code here
    }