尝试附加结构数组时发生突变错误
Mutating error when attempting to append an array of a struct
我正在尝试在 SwiftUI Form
中创建一个操作以向我的数据集添加额外的 Child
。当我尝试附加 newChild
时出现错误:
Cannot use mutating member on immutable value: 'self' is immutable
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
是可变的,所以为什么会出现此错误?
问题是我在它被变异的结构中声明了我的数组 children
。将声明移出结构 运行 没有错误。
问题是 struct
无法更改其自身的属性,除非正在更改这些属性的函数被标记为 mutating
。您不能将 body
标记为 mutating
,但可以将 children
标记为 @State var
。 @State
变量是可变的,但只能来自您的视图 body
属性。
我正在尝试在 SwiftUI Form
中创建一个操作以向我的数据集添加额外的 Child
。当我尝试附加 newChild
时出现错误:
Cannot use mutating member on immutable value: 'self' is immutable
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
是可变的,所以为什么会出现此错误?
问题是我在它被变异的结构中声明了我的数组 children
。将声明移出结构 运行 没有错误。
问题是 struct
无法更改其自身的属性,除非正在更改这些属性的函数被标记为 mutating
。您不能将 body
标记为 mutating
,但可以将 children
标记为 @State var
。 @State
变量是可变的,但只能来自您的视图 body
属性。