@State not initializing correctly

Hello, I come across a problem I cannot solve, also the stack overflow results don’t show the solution. I also searched this forum.
I have to Integer variables which are in a Textfield and want to make a mathematic addition and present it as a variable in a Text. But the Initialization does not work correctly
That’s what I want to achieve
var var1 = 1
var var2 = 2
var result = (var1 * 75) + (var2 * 85)

That’s my solution but it does not work unfortunately

Thanks for reading

import SwiftUI

class Crew {
var var1:Int = 1
var var2:Int = 2
var result:Int = (var1 * 75) + (var2 *85)


init(var1: Int, var2: Int, result: Int) {
    _var1 = State(initialValue: 1)
    _var2 = State(initialValue: 2)
    _result = State(initialValue: 3)
}

}


 struct DOWView: View {
    
   @State var crew = Crew()
    
    
var body: some View {
    
    VStack {
        TextField("#", value: $crew.var1, format: .number)
        TextField("#", value: $crew.var2, format: .number)
        Text("\(crew.result)")
        
        
    }
    
    struct DOWView_Previews: PreviewProvider {
        static var previews: some View {
            DOWView()
        }
    }

I don't remember if that's official guideline or not, and I don't remember whether it is possible or impossible to check for it statically, but here it goes: "don't use reference types for State variables".

If you want to continue with a separate model object (e.g. to have view / model separation) – then mark Crew as ObservableObject, make it's two stored variables Published, make the third result property dynamic (calculated on the fly in the getter (and there is no need for a setter)), remove explicit init(...) which is unneeded here, and finally reference Crew as private StateObject variable in your view. OTOH, if you are after the "minimal line count" example and don't mind having "model logic in your view" (which is bad for big projects but ok in small or tests projects) you can completely remove your Crew object, have the two stored variables as private State variables in your view, and again, calculate the result value on the fly.

There's one case when you'd not want to calculate result value on the fly – if it's expensive – but that's not the case here and you'll cross that bridge when you get to it.

1 Like

Thank you. That worked for me.