Hi I want to create an array of Views, each view has a button to append the array.
Here is my code
struct ContentView: View {
@State var views = [ButtonView]()
let firstButton = ButtonView(id: 1, addView: { views.append(secondButton)})
let secondButton = ButtonView(id: 2, addView: {})
var body: some View {
VStack {
ForEach(views, id: \.id) { $0
}
}
.onAppear{
views.append(firstButton)
}
}
}
struct ButtonView: View {
var id: Int
let addView: () -> Void
var body: some View {
Button("Add View") {
addView()
}
}
}
then I got the errors:
Cannot use instance member 'secondButton' within property initializer; property initializers run before 'self' is available
Cannot use instance member 'views' within property initializer; property initializers run before 'self' is available
I did search and didn't find anything related, then I asked chatGPT, chatGPT updated my code
struct ContentView: View {
@State private var views = [ButtonView]()
private lazy var firstButton = ButtonView(id: 1) { [weak self] in
self?.views.append(self!.secondButton)
}
private let secondButton = ButtonView(id: 2) {}
var body: some View {
VStack {
ForEach(views, id: \.id) { $0 }
}
.onAppear {
views.append(firstButton)
}
}
}
struct ButtonView: View {
let id: Int
let addView: () -> Void
var body: some View {
Button("Add View") {
addView()
}
}
}
Then I got another error Cannot use mutating getter on immutable value: 'self' is immutable
on the line views.append(firstButton)
and ChatGPT never solve this error after several tries.
How to make it works? thank you if you could leave me some clue.