peterk
peterk

Reputation: 329

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?

Upvotes: 7

Views: 2339

Answers (2)

Asperi
Asperi

Reputation: 257779

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
}

Upvotes: 12

Shehata Gamal
Shehata Gamal

Reputation: 100513

You can try

@AppStorage("IsSigned") var isSigned = false

Upvotes: 0

Related Questions