gpt4 book ai didi

swift - 如何将变量存储为 @AppStorage 变量的键

转载 作者:行者123 更新时间:2023-12-05 01:33:00 36 4
gpt4 key购买 nike

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?

最佳答案

您可以分离 id 依赖 subview 并动态初始化 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
}

关于swift - 如何将变量存储为 @AppStorage 变量的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64937323/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com