Home > OS >  Applying of an API on Bar chart to represent data give error swiftUI
Applying of an API on Bar chart to represent data give error swiftUI

Time:11-04

How can I create 1 chart that represent an array of points rather than creating a multiple charts that represent different value.... What can you recommend to use instead of ForEach...

Challenge:

             ForEach(vm.res) { resul in             
   BarChartView(data: ChartData(values: [("",resul.new_cases)]), title: "")
                
            }

Unfortunately I get this outcome.

enter image description here

However I am required of creating something simmilar to this:

Requirement:

    BarChartView(data: ChartData(values: [

                ("Jan", 12),
                ("Feb", 5),
                ("Mar", 10),
                ("Apr", 7),
                ("May", 6),
                ("Jun", 18),
                ("Jul", 21),
                ("Aug", 1),
                ("Jul", 21),
                ("Aug", 1),

            ]),
                            title: "")

enter image description here

After my API Fetch I want data to be represented on the BarChart, however I can not, I am trying to replace the doubles in the array of values with data from Doubles from an api... However it repeating itself, I believe the problem is with FOR EACH or ID

I Have used this Swift Package Manager for reference...

https://github.com/AppPear/ChartView

CodePudding user response:

You are doing:

ForEach(vm.res) { resul in 
    BarChartView(data: ChartData(values: [("",resul.new_cases)]), title: "")
}

And you get n BarCharView.

So, you are doing the ForEach() at the wrong place.

You could explicitly do:

var values: [(String, Double)] = []
for aResult in vm.res {
    let newValue = ("", aResult.new_cases)
    values.append(newValue)
}
BarChartView(data: ChartData(values: values), title: "")

With a more high level method: map():

BarChartView(data: ChartData(values: vm.res.map{ ("", $0.new_cases)}),  
             title: "")
  • Related