I am trying to create an apple watch app that calculates Karvonen value.
When I inserted func calculation into struct
, I kept receiving the Swift Compiler Error that says:
[Type "FourthView"does not conform to protocol "View"]
I understood that I should not be calculating inside the func
, but I don't know how to solve this problem.
struct FourthView: View{
@Binding var fourthScreenShown:Bool
//@State var RHR:Int
//@State var weight:Int
@State var Age:Int
@State var ExerciseIT = 0.3
@State var ConstantNumber = 220
@State var RHR = 68
func karvonen(cn: Int, rhr: Int, age: Int, ei:Double) -> Double {
return Double((cn-age-rhr)) * ei + Double(rhr)
let output = karvonen(cn: ConstantNumber, rhr: RHR, age: Age, ei: ExerciseIT)
var body: some View {
VStack{
Text("Your Kar is")
.font(.system(size: 14))
Text("\(output)")
.font(.system(size: 40))
}
}
}
}
The var body
has to exist at the top level of the struct
for it to conform to View
. Right now, you have var body
inside your func
.
struct FourthView: View{
@Binding var fourthScreenShown:Bool
@State var Age:Int
@State var ExerciseIT = 0.3
@State var ConstantNumber = 220
@State var RHR = 68
func karvonen(cn: Int, rhr: Int, age: Int, ei:Double) -> Double {
return Double((cn-age-rhr)) * ei + Double(rhr)
}
var body: some View {
VStack{
Text("Your Kar is")
.font(.system(size: 14))
Text("\(karvonen(cn: ConstantNumber, rhr: RHR, age: Age, ei: ExerciseIT))")
.font(.system(size: 40))
}
}
}
Another equivalent version (maybe useful if you have to use the result in multiple places):
var body: some View {
let output = karvonen(cn: ConstantNumber, rhr: RHR, age: Age, ei: ExerciseIT)
VStack{
Text("Your Kar is")
.font(.system(size: 14))
Text("\(output)")
.font(.system(size: 40))
}
}
Unrelated to your issue, but a hint for the future: in Swift, generally, variables/parameters are camel cased. So, your Age
, ExerciseIT
, etc would be age
, exerciseIT
, etc.
Also, unless you're changing the values, you don't need @State
in front of all of the parameters. ConstantNumber
, for example (if the name is accurate), probably doesn't need to be @State
.