Cannot convert value of type 'Float' to expected argument type 'Binding<Float>' Error Swift 5.2

Viewed 1900

I'm trying to refactor my code with MVVM pattern design, everything goes fine till I reached to one of my project properties which is a Float number that published from viewModel file and become observed in ContentView file to show the percentage of a progress bar. My understanding on this subject is very primitive, so I need serious help. Below is the section of my code from view and viewModel files of my project which related to the error I get:

//-----------------------ContentView File

import SwiftUI


struct ContentView: View {
    @ObservedObject var quizBrain = QuizBrain()
    var body: some View {
        VStack {
            ProgressBar(barValue: quizBrain.progBarPercentage).frame(height: 35) }  
// Here I get this error: Cannot convert value of type 'Float' to expected argument type 'Binding<Float>'

struct ProgressBar: View {
    @Binding var barValue: Float
    var body: some View {
        GeometryReader { geometry in
            ZStack(alignment: .leading) {
                Rectangle().frame(width: geometry.size.width , height: geometry.size.height)
                    .opacity(0.3)
                    .foregroundColor(Color(UIColor.systemTeal))
                Rectangle().frame(width: min(CGFloat(self.barValue)*geometry.size.width, geometry.size.width), height: geometry.size.height)
                    .foregroundColor(Color(UIColor.systemBlue))
                    .animation(.linear)
            }.cornerRadius(45.0)
        }
    }
}



//--------------------ViewModel File


import Foundation

class QuizBrain: ObservableObject {
@Published var x = 10       //a method generate this Int
@Published var y = 8        //a method generate this Int
@Published var progBarPercentage : Float = 0.0

func progressBarFunc() {
      progBarPercentage = Float(y)/Float(x)
    }
}
3 Answers

You have to use the binding of your quizBrain object rather than progBarPercentage's Float value.

struct ContentView: View {
    @ObservedObject var quizBrain = QuizBrain()
    var body: some View {
        VStack {
            ProgressBar(barValue: $quizBrain.progBarPercentage).frame(height: 35)
            // Add $ to create a two way binding
        }
    }
}

To access binding from @Published value you should use projectedValue via '$', like below

var body: some View {
    VStack {
        ProgressBar(barValue: $quizBrain.progBarPercentage).frame(height: 35) }  

Bezi, in this case the argument needs to be a binding of type Binding<Float> you're missing the "$".

Related