Swift(UI) 错误:无法在不可变值上使用可变成员:“self”是不可变的

blk*_*sld 1 mutable swift swiftui

基本上我想要做的是如果你按下按钮然后条目应该得到一个新的 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()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

}


类 CEntries

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

    init(string1: String, string2: String) {
        self.string1 = string1
        self.string2 = string2
    }
}
Run Code Online (Sandbox Code Playgroud)

New*_*Dev 5

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

@State var entries: [CEntries] = []
Run Code Online (Sandbox Code Playgroud)

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

而且它是一个ObservableObject.

而是CEntries改为 a struct- a 值类型,这样如果它改变,值本身也会改变:

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()
          }
      }
   }
}
Run Code Online (Sandbox Code Playgroud)