如何将变量存储为 @AppStorage 变量的键
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?
你可以试试
@AppStorage("IsSigned") var isSigned = false
您可以分离 id
依赖子视图并动态初始化 AppStorage
属性 包装器。
这是一个解决方案。使用 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
}
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?
你可以试试
@AppStorage("IsSigned") var isSigned = false
您可以分离 id
依赖子视图并动态初始化 AppStorage
属性 包装器。
这是一个解决方案。使用 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
}