When you post a question,
you should explain what you expect, what you get,
where in code the exact miscalculation occurs.
provide complete code (calculate() is nowhere used)
In anycase, calculate is flawed (and prevents from compiling): heightCms is declared as Double and you set as String
In addition, please use Paste and Match Style to avoid all the extra blank lines that make code nearly impossible to grasp. That was already a comment on your previous post.
BTW: you never provided feedback on this previous post. Was it solved ?
struct ContentView: View {
@State var height = ""
@State var heightCms: Double = 0.0
var heightOptions = ["cms", "inches"]
@State private var heightselection = "cms"
var body: some View {
VStack {
HStack {
Text("Height:")
.font(.title)
.foregroundColor(.black)
Spacer()
TextField("Height", text: $height)
.frame(width: 150, height: 50)
Picker("Select Height Units: ", selection: $heightselection, content: {
ForEach(heightOptions, id: \.self) {
Text($0)
}
})
Spacer()
}
Text("You selected: \(heightselection)")
Text("Height in Cms: \(heightCms)")
}.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
extension ContentView {
func calculate() {
heightCms = heightselection == "cms" ? String(Double(height)) : (String(Double(height)) * 2.54)
}
}
This should work better (You need also to calculate when text is entered):
struct ContentView: View {
@State var height = ""
@State var heightCms: Double = 0.0
var heightOptions = ["cms", "inches"]
@State private var heightselection = "cms"
func calculate() { // You can also put it in an extension as you did in your code
heightCms = heightselection == "cms" ? (Double(height) ?? 0.0) : 2.54 * (Double(height) ?? 0.0)
}
var body: some View {
VStack {
HStack {
Text("Height:")
.font(.title)
.foregroundColor(.black)
Spacer()
TextField("Height", text: $height)
.frame(width: 150, height: 50)
.onChange(of: height) { _ in calculate() }
Picker("Select Height Units: ", selection: $heightselection, content: {
ForEach(heightOptions, id: \.self) {
Text($0)
}
})
.onChange(of: heightselection) { _ in calculate() }
Spacer()
}
Text("You selected: \(heightselection)")
Text("Height in Cms: \(heightCms)")
}.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}