Newbie needs help with SwiftUI

Simple program to allow user to input weight in pounds or Kg and then print weight in Kg. The below code gives error: "Type '()' cannot conform to 'View'. Any help is greatly appreciated.

inline-codeimport SwiftUI".

struct ContentView: View {

@State private var weight = 175.0

@State private var weightKg = 0.0

@State private var ifPounds: Bool = true

var body: some View {

VStack {

  HStack {

    Text("Select unit for weight:")



    Toggle("", isOn: $ifPounds)

      .labelsHidden()

      .background(Color.green)

      .clipShape(Capsule())

     

    Text(ifPounds ? "Pounds" : "Kg")

      .padding()

  } // HStack

        

  if (ifPounds == true) {

    weightKg = weight/2.205

  } else {

    weightKg = weight

  }

   

  Text("Your weight is \(weightKg, specifier: "%.1f") ")

   

} //Vtack

} //Some View

} //Content View

struct ContentView_Previews: PreviewProvider {

static var previews: some View {

ContentView()

}

}

Answered by SWSharpy in 739853022

Thank you Dirk-FU. In retrospect, your explanation makes sense and I am beginning to wrap my head around declarative vs. imperative programming.

You are still thinking to much in "imperative programming" terms. SwiftUI is "declarative". The var body of a View is no regular Swift function, it is a @ViewBuilder. This means only a subset of Swift is allowed there. Like generating Views and some conditional statements. Regular "imperative" code like weightKg = weight/2.205 is not allowed.

You have to derive all of the View's state from your model. Some Views like Button have closures which can contain "imperative" code. You can do/cause calculations there or in your model.

Better would be to bind the weight variable to the input field of a View and make a calculated var for the other weight which is used by a Text for example.

@State var weight = 175.0
var weightKg:Double{
   return weight/2.205
}

var body:some View{
// ...
   SomeInput($weight) // SomeInput is not really an existing type, you would have to look up the correct syntax for TextField for example
   Text("weight in kg: \(weightKg)")
// ...
}
Accepted Answer

Thank you Dirk-FU. In retrospect, your explanation makes sense and I am beginning to wrap my head around declarative vs. imperative programming.

Newbie needs help with SwiftUI
 
 
Q