5

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?

peterk
  • 319
  • 3
  • 10

2 Answers2

9

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
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • Ok so what I did was I used your variable declaration then in my previous view where I present the view with its variables I put in the Appstorage(wrappedValue: false, id) and it was working perfectly! – peterk Nov 22 '20 at 19:12
0

You can try

@AppStorage("IsSigned") var isSigned = false
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • No there is no way I can use that, as I said I need to use the variable as this a view in a forEach where there are multiple id's not just one that I can use. – peterk Nov 21 '20 at 00:09