【问题标题】:Mutating error when attempting to append an array of a struct尝试附加结构数组时发生变异错误
【发布时间】:2020-01-01 01:38:50
【问题描述】:

我正在尝试在 SwiftUI Form 中创建一个操作,以向我的数据集添加一个额外的 Child。当我尝试附加 newChild 时,出现错误:

不能对不可变值使用可变成员:“self”是不可变的

struct Child : Identifiable {

   var id = UUID()
   var birthday: Date
   var name: String

}

struct ContentView: View {

    var children : [Child] = []

    var body: some View {

        VStack {
              Button(action: {
                  let newChild = Child(birthday: Date(), name: "Carl")
                  children.append(newChild)
              }) {
                  Text("Add Child")
              }
        }
    }
}

据我所知,我的数组 children 是可变的,那么为什么会出现此错误?

【问题讨论】:

    标签: ios swift struct immutability swiftui


    【解决方案1】:

    问题是struct 无法更改自己的属性,除非更改这些属性的函数被标记为mutating。您不能将body 标记为mutating,但可以将children 标记为@State var@State 变量是可变的,但只能在视图的 body 属性内。

    【讨论】:

      【解决方案2】:

      问题是我在它被突变的结构中声明了我的数组children。将声明移到结构之外运行没有错误。

      【讨论】:

        猜你喜欢
        • 2021-07-06
        • 2015-01-13
        • 1970-01-01
        • 2021-05-18
        • 1970-01-01
        • 1970-01-01
        • 2022-01-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多