'why can't I change the value of a var named coma after and if statement

I'd like to change the value of comma to true if a string contains a comma xcode swfitui

struct ContentView: View {
        @State var dos = ""
        @State var coma : Bool = false
        
        var body: some View {
            Form {
            TextField("dosis", text: $dos)
                
                if dos.contains(",") == true {
                    
                   coma = true
                }
            }
    }
    }


Solution 1:[1]

You cannot put that type code wherever you like in a View. The view expect to show other views, and your if is not returning a view. Try this approach where your if is in a modifier, or a function:

struct ContentView: View {
    @State var dos = ""
    @State var coma = false
    
    var body: some View {
        Form {
            TextField("dosis", text: $dos)
                .onChange(of: dos) { doz in
                    if doz.contains(",") {
                        coma = true
                    }
                    print("--> dos: \(dos)  coma: \(coma)")
                }
        }
    }
}

You can also use: .onSubmit {...}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1