Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

ios - Mutating an array within a view from a subview "Cannot use mutating member on immutable value: 'self' is immutable"

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

SwiftUI view is struct you cannot mutate it from within self. Make notes as @State then you can use

    @State var notes: [String] = []

    // .. other code

    func addNote(note: String) {
        notes.append(note)
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...