swiftswiftuiswiftui-previews

Cannot convert value of type 'Int.Type' to expected argument type 'Int' - Swift


What I am trying to do here is to move the value of "KarvonenVal" to SummaryView using NavigationLink.

struct CalcProcess: View{
    @EnvironmentObject var workoutManager: WorkoutManager

    @State var NumAdded4 = false
    @State var Age:Int
    @State var ExerciseIT:Int
    @State var ConstantNumber = 220
    @State var RHR:Int
    @State var KarvonenVal = 1
    
    
    func karvonen(cn: Int, rhr: Int, age: Int, ei:Double) -> Double {
        return Double((cn-age-rhr)) * (ei / 10) + Double(rhr)
    }
    
    var body: some View {
        let output = karvonen(cn: ConstantNumber, rhr: RHR, age: Age, ei: Double(ExerciseIT))
        let roundedDouble = Double(round(1000*output)/1000)
        let KarvonenVal: String = String(format: "%.1f", roundedDouble)
           
        VStack{
            Text("\(KarvonenVal)")
                .foregroundStyle(.black)
        }
        NavigationLink(destination: SummaryView(NumAdded4: $NumAdded4, KarvonenVal: KarvonenVal), isActive: $NumAdded4, label: {Text("Next")})
        }
    }
}


struct KarvonenCalc_Previews: PreviewProvider {
    static var previews: some View {
        KarvonenCalc(KarvonenVal: Int)
    }
}

However, I kept receiving error at "KarvonenCalc_Previews" that says "Cannot convert value of type 'Int.Type' to expected argument type 'Int'". I am literally stuck here, and cannot display KarvonenVal at SummaryView.

struct KarvonenCalc_Previews: PreviewProvider {
    static var previews: some View {
        KarvonenCalc(KarvonenVal: Int)
    }
}

Also at SummaryView_Preview, I received the simillar error that says "Cannot convert value of type 'String.Type' to expected argument type 'String'".

struct SummaryView_Previews: PreviewProvider {
    static var previews: some View {
        SummaryView(NumAdded4: .constant(false), KarvonenVal: String)
    }
}

Solution

  • If you are using variables/constants, it's a convention thing of having them lowercased. For types, they're uppercased.

    So use 'karvonenVal' instead of 'KarvonenVal'. You are also using two properties with the same name:

    let KarvonenVal: String = String(format: "%.1f", roundedDouble)
    

    In the body and

    @State var KarvonenVal = 1
    

    right above as your struct property, so compiler is probably confused about which one to use and since they're both uppercased, it reads it as 'types' not as properties.

    What you need to do is resolve name conflict between 'KarvonenVal'(rename one of them to something like 'KarvonenVal0' or whatever you like) and make all property names lowercased.

    For preview you'll have to provide default values for it to work. It's basically asking you for some number that is an Integer and you're giving it the Integer Type. In other words it's asking for 'an object' and you're giving it 'a class'.