Reputation: 427
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
Upvotes: 0
Views: 757
Reputation: 16341
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")
}
Upvotes: 2