UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Cannot use instance member 'xxx' within property initializer; property initializers run before 'self' is available

Forums > SwiftUI

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.

2      

I would suggest not doing it like this.

Instead, do something like this:

struct ContentView: View {
    @State private var buttons: [ButtonData] = []

    var body: some View {
        VStack {
            ForEach(buttons) { button in
                Button("Add View") {
                    addButton()
                }
            }
        }
        .onAppear {
            buttons.append(ButtonData(id: 1))
        }
    }

    func addButton() {
        if let lastID = buttons.last?.id {
            buttons.append(ButtonData(id: lastID + 1))
        }
    }
}

struct ButtonData: Identifiable {
    let id: Int
}

3      

Hi @roosterboy, thank you very much.

I choose to write that way, because I want to add different kind of View next, there will be diferent button to add different view.

Beyond that, I just want to know why I got the error Cannot use mutating getter on immutable value: 'self' is immutable what it means? what's fundamental law of it, or the deep knowlodge I missed.

And is it possible to make my code work, sorry I can't get rid of my OCD 😂

2      

If you have a struct

struct Person {
    var name: String

    func makeAnonymous() {
        name = "Anonymous" // ERROR Cannot assign to property: 'self' is immutable
    }
}

so you have to tell it that that you changing it

struct Person {
    var name: String

    mutating func makeAnonymous() {
        name = "Anonymous"
    }
}
var person = Person(name: "Ed")

print(person) // prints Person(name: "Ed")

person.makeAnonymous()

print(person) // prints Person(name: "Anonymous")

Check out Mutating methods

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.