SwiftUI:@AppStorage 使用中的“属性初始值设定项在‘self’可用之前运行”

时间:2021-07-29 21:25:20

标签: swift xcode swiftui properties picker

我是 Swift 的新手,想解决这个问题。我希望,当我关闭并返回应用程序时,选择器中的货币会被保存。 (通过@AppStorage)但是我不能使用任何我想到的东西来定义@AppStorage 中的 $currency 到 $cur。谢谢你的帮助!代码如下:

//Settings
struct SettingsView: View {

@State private var currency = "$"
var currencies = ["$", "€", "¥", "£"]
@AppStorage("name") var name = ""
@AppStorage("cur") var cur = "\($currency)"
//Cannot use instance member '$currency' within property initializer; property initializers run before 'self' is available

var body: some View {
    NavigationView {
        
        Form {
            Section(header: Text("Your name")) {
                TextField("Tim", text: $name)
            }
            
            Section(header: Text("Your currency")) {
                Picker(selection: $currency, label: Text("Your Currency")) {
                    ForEach(currencies, id: \.self) {
                        Text($0)
                    }
                }
                .pickerStyle(SegmentedPickerStyle())
            }
        }
        
    }
    .navigationTitle("Settings")
    }
}

1 个答案:

答案 0 :(得分:0)

在定义 $currency 时不能引用 cur。这是 Swift 的一个限制。很明显,货币已经有一个值,但 Swift 不会让你使用它,直到初始化程序完成设置 self.这与 AppStorage 无关——这是一条规则,属性初始值设定项不能引用其他(非静态)属性。

所以,这个

@State private var currency = "$"
@AppStorage("cur") var cur = "\($currency)"

可能

@State private var currency = "$"
@AppStorage("cur") var cur = "$" // set it to the same value

private static let dollar = "$"

@State private var currency = SettingsView.dollar
@AppStorage("cur") var cur = SettingsView.dollar