本文介绍了从子视图改变视图中的数组“不能在不可变值上使用可变成员:'self'是不可变的"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在结构(swiftui 视图)中调用一个函数,该函数将一个项目附加到一个数组,然后该数组被映射到一个列表.正在子视图中调用该函数,但我不断收到错误无法在不可变值上使用变异成员:'self' 是不可变的".

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".

这是父级中的函数:

mutating func addNote(note: String){
        var newNotes = notes;
        newNotes.append(note);
        notes = newNotes;
    }

体内有:

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")
}

我的 addNoteView() 看起来像这样:

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!

推荐答案

SwiftUI 视图是一种结构,你不能从自身内部改变它.将 notes 设为 @State 然后就可以使用了

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)
    }

这篇关于从子视图改变视图中的数组“不能在不可变值上使用可变成员:'self'是不可变的"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 22:02