I'm attempting to call a function in a struct (swiftui view) which appends an item to an array that is then mapped to a list. The function is being called in a subview, but I keep getting the error "Cannot use mutating member on immutable value: 'self' is immutable".
Heres the function in the parent:
mutating func addNote(note: String){
var newNotes = notes;
newNotes.append(note);
notes = newNotes;
}
Inside the body has:
List {
ForEach(notes, id: .self) { string in
Section(header: Text("1/22/20")){
Text(string)
}
}...
To pass the function to the subview i try this:
NavigationLink(destination: AddNoteView(delegate: addNote)) {
Text("Add note")
}
and my addNoteView() looks like this:
struct AddNoteView : View {
@State var note: String = ""
@Environment(.presentationMode) var presentationMode: Binding<PresentationMode>
var delegate: (String) -> ()
var body: some View {
NavigationView{
Form{
Section(header: Text("Note")){
TextField("Note", text:$note)
}
Section(){
Button(action: {
delegate(note)
presentationMode.wrappedValue.dismiss()}){
Text("Add note")
}
Anyone having any clue what I'm doing wrong? Thank you so much!
question from:
https://stackoverflow.com/questions/65849089/mutating-an-array-within-a-view-from-a-subview-cannot-use-mutating-member-on-im 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…