Why Does Method Force Me To Add Mutating

Regardless if I use a protocol or not that contains this method, e.g. I have this

var test: String?

func setupData() -> Void {
   test = "New value"
}

Why does it say

Cannot assign to property: 'self' is immutable"

So if i add mutable to setupData() which becomes "mutating func setupData() { ... }", then i get another error message

Cannot use mutating member on immutable value: 'self' is immutable

I call setupData in onAppear() instead of init() for now. Putting it in init forces me to initialize the variables (sucks)

I am lost on this one. Advise?

This is used inside a Struct View. not a class.

Answered by Claude31 in 731773022

Could you show the complete struct ? That will make it much easier to answer.

This works , with a State var. No mutating.

struct Test: View {
    @State var test: String?

    func setupData() -> Void {
       test = "New value"
    }
    
    var body: some View {
        Text(test ?? "---")
            .onAppear(){ setupData() }
    }
}

If you need Swift without SwiftUI (as the tag hints), this works (tested in playground)

struct Test {
    var test: String?
    mutating func setupData() -> Void {
       test = "New value"
    }
}

var t = Test()
t.setupData()
print(t.test)
Accepted Answer

Could you show the complete struct ? That will make it much easier to answer.

This works , with a State var. No mutating.

struct Test: View {
    @State var test: String?

    func setupData() -> Void {
       test = "New value"
    }
    
    var body: some View {
        Text(test ?? "---")
            .onAppear(){ setupData() }
    }
}

If you need Swift without SwiftUI (as the tag hints), this works (tested in playground)

struct Test {
    var test: String?
    mutating func setupData() -> Void {
       test = "New value"
    }
}

var t = Test()
t.setupData()
print(t.test)
Why Does Method Force Me To Add Mutating
 
 
Q