Swift(UI) Error: Cannot use mutating member on immutable value: 'self' is immutable

Swift(UI) Error: Cannot use mutating member on immutable value: 'self' is immutable

基本上我想要做的是,如果您按下按钮,那么条目应该获得一个新的 CEntry。如果有人可以帮助我,那就太好了。谢谢!

struct AView: View {

   var entries = [CEntries]()

   var body: some View {
       ZStack {
           VStack {
               Text("Hello")
               ScrollView{
                   ForEach(entries) { entry in
                       VStack{
                        Text(entry.string1)
                        Text(entry.string2)
                    }
                }
            }
        }
        Button(action: {
            self.entries.append(CEntries(string1: "he", string2: "lp")) <-- Error
        }) {
            someButtonStyle()
        }
    }
}

}


Class 个条目

 class CEntries: ObservableObject, Identifiable{
    @Published var string1 = ""
    @Published var string2 = ""

    init(string1: String, string2: String) {
        self.string1 = string1
        self.string2 = string2
    }
}

视图在 SwiftUI 中是不可变的。您只能改变它们的状态,这是通过更改具有 @State 属性 包装器的属性来完成的:

@State var entries: [CEntries] = []

但是,虽然您可以这样做,但在您的情况下 CEntries 是 class - 即引用类型 - 因此虽然您可以检测到 entries 数组中的变化 -添加和删​​除元素,您将无法检测到元素本身的变化,例如,当 .string1 属性 更新时。

它是 ObservableObject

也无济于事

相反,将 CEntries 更改为 struct - 值类型,这样如果它发生变化,值本身也会发生变化:

struct CEntries: Identifiable {
    var id: UUID = .init()
    var string1 = ""
    var string2 = ""
}

struct AView: View {

   @State var entries = [CEntries]() 

   var body: some View {
       VStack() {
          ForEach(entries) { entry in
             VStack {
                Text(entry.string1)
                Text(entry.string2)
             }
          }
          Button(action: {
            self.entries.append(CEntries(string1: "he", string2: "lp"))
          }) {
              someButtonStyle()
          }
      }
   }
}