0

I am trying to make a macOS list/todo app with swift and want to add a button that adds appends a struct to an array, but it shows this error: "Cannot use mutating member on immutable value: 'self' is immutable" here is my code


import SwiftUI

struct Lists{
    var title : String
    var id = UUID()
}


struct SidebarView: View {
    var list = [Lists(title: "one"),Lists(title: "two"),Lists(title: "three")]
    
    
    var body: some View {
        
       List{

            Button(action:{
                let item = Lists(title:"hello")
                list.append(item)
            }) {
                Text("add")
            }

        
            ForEach(list, id : \.id ){ item in
                NavigationLink(destination:DetailView(word:item.title)){
                    Text(item.title)
                }
            }
        }
       .listStyle(SidebarListStyle())
       .frame(maxWidth:200)
                  
    }
}

struct SidebarView_Previews: PreviewProvider {
    static var previews: some View {
        SidebarView()
    }
}

the code that says list.append is the error

1 Answer 1

2

You need to declare list as @State variable.

@State var list = [Lists(title: "one"),Lists(title: "two"),Lists(title: "three")]

Then append new item to list:

Button(action:{
    let item = Lists(title:"hello")
    self.list.append(item)
}) {
    Text("add")
}
Sign up to request clarification or add additional context in comments.

2 Comments

can you explain why do I need to add self to the list.append?
Take a look at stackoverflow.com/questions/32665326/…. It explains clearly why self is required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.