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

koen
  • 5,383
  • 7
  • 50
  • 89
Tony Zhang
  • 417
  • 4
  • 8

1 Answers1

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")
}
Frankenstein
  • 15,732
  • 4
  • 22
  • 47
  • 1
    can you explain why do I need to add `self ` to the `list.append?` – Tony Zhang Jul 19 '20 at 19:17
  • Take a look at https://stackoverflow.com/questions/32665326/reference-to-property-in-closure-requires-explicit-self-to-make-capture-seman. It explains clearly why `self` is required. – Frankenstein Jul 19 '20 at 19:20