SwiftUI call mutating func from var body

I was working on the same article.

I didn't get this problem because I was already using the @State property wrapper. As suggested by kontiki Session 226 (Data Flow Through SwiftUI) is great for understanding how to use which property wrapper when you are updating the data different source.

And If you want to know what is @State this answer has it all.

Here is my code:

@State var rTarget = Double.random(in: 0..<1)
@State var gTarget = Double.random(in: 0..<1)
@State var bTarget = Double.random(in: 0..<1)
@State var rGuess: Double
@State var gGuess: Double
@State var bGuess: Double

It is hard to tell what is recommended in your case, because in your example you are not showing us what the target variables are actually for.

However, I think it is safe to say that in SwiftUI views, variables that need to change over time, must be either @State or of one of the binding types available to you. Otherwise, it most likely need to be unmutable.

It all comes down to determine what is the "source of truth". If those targets are something internal to the view, then use @State, if the source of truth is external to the view, you would go for one of the bindable options.

I strongly recommend you invest the 37 minutes it takes to watch WWDC2019, Session 226 (Data Flow Through SwiftUI). It will clear all your questions about this.

If you are in a hurry, jump to 5:45. But I do recommend you watch the whole thing. It will save you time eventually.

If you don't know what the "source of truth" is. Then you should definitely must watch the session.


Only solution I found at this point is to also mark the xTarget props as @State and modify them without mutating funcs

@State private var rTarget = Double.random(in: 0..<1)
@State private var gTarget = Double.random(in: 0..<1)
@State private var bTarget = Double.random(in: 0..<1)

But it's not clear to me that it's good practice.