SwiftUI: "Property initializers run before 'self' is available" 在@AppStorage 使用
SwiftUI: "Property initializers run before 'self' is available" in @AppStorage use
我是 Swift 的新手,想解决这个问题。我希望,当我关闭并返回应用程序时,选择器中的货币会被保存。 (通过@AppStorage)但是我无法使用我想到的任何东西来将$currency 定义为@AppStorage 中的$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([=11=])
}
}
.pickerStyle(SegmentedPickerStyle())
}
}
}
.navigationTitle("Settings")
}
}
定义cur
时不能引用$currency
。这是 Swift 的限制。很明显,货币已经有一个值,但是 Swift 不会让你使用它,直到初始化程序完成自我设置。这与 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
我是 Swift 的新手,想解决这个问题。我希望,当我关闭并返回应用程序时,选择器中的货币会被保存。 (通过@AppStorage)但是我无法使用我想到的任何东西来将$currency 定义为@AppStorage 中的$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([=11=])
}
}
.pickerStyle(SegmentedPickerStyle())
}
}
}
.navigationTitle("Settings")
}
}
定义cur
时不能引用$currency
。这是 Swift 的限制。很明显,货币已经有一个值,但是 Swift 不会让你使用它,直到初始化程序完成自我设置。这与 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