【问题标题】:SwiftUI: "Property initializers run before 'self' is available" in @AppStorage useSwiftUI:@AppStorage 使用中的“属性初始化程序在 'self' 可用之前运行”
【发布时间】:2021-10-05 12:37:02
【问题描述】:

我是 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")
    }
}

【问题讨论】:

    标签: swift xcode swiftui properties picker


    【解决方案1】:

    定义cur 时不能引用$currency。这是 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
    

    【讨论】:

    • 感谢您的回答,但我无法将货币保存在 AppStorage 的选择器中。你知道吗,我是怎么做到的?谢谢!!
    • 这是一个不同的问题。请单独发布。
    猜你喜欢
    • 2017-09-18
    • 1970-01-01
    • 2021-10-02
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-03
    相关资源
    最近更新 更多