我找到的答案是一级结构。在我的代码中,我想找出结构的结构内部有多少相同的日期。我以前从未使用过 equatable,所以我不确定如何在 struct 中使用 struct 来实现它。
我正在使用 Charts pod,并且该数组chartMetricItemSets
包含多天的不同读数。例如:["name": sugar, [["date": "Oct 10", "value": 120], ["date": "Oct 10", "value": 121], ["date": "Oct 11", "value": 120], ["date": "Oct 13", "value": 120], ["date": "Oct 13", "value": 121]]
。将xAxisDates
是["Oct 10", "Oct 11", "Oct 13"]
x 是日期,y 是相同日期的总和
目标:chartDataEntries 应该附加[x:0(10/10), y:241], [x:1(10/11), y:120], [x:2(10/13), y: 241]
谢谢!
struct ChartData {
let name: String
let value: [ChartValue]
}
struct ChartValue {
let date: Date
let value: Double
}
var chartMetricItemSets = [[ChartData]]()
var xAxisDates = [String]() //date array
func getChartDataSets() {
for (index, chartHealthItemSet) in chartMetricItemSets.enumerated() {
let dataSourceSelected = dataSourcesSelected[index]
var chartDataEntries = [ChartDataEntry]() //array display on graph
var chartYaxis: Double = 0
var datePoint: Int = 0
var countChartYaxis = 0
var duplicateDateCount = 0
for (index, item) in chartHealthItemSet[0].value.enumerated() {
for (dateIndex, date) in xAxisDates.enumerated() {
if item.date.convertDateToString(dateFormat: .monthDay) == date {
chartYaxis += item.value
datePoint = dateIndex
chartYaxis += 1
break
}
//missing counting duplicateDateCount
if duplicateDateCount == countChartYaxis {
chartDataEntries.append(ChartDataEntry(x: Double(datePoint), y: chartYaxis.roundUpNDecimal(n: 2)))
}
}
print("chartYaxis: \(chartYaxis)")
print("chartDataEntries: \(chartDataEntries)")
}
chartDataEntries.sort(by: { $0.x < $1.x })
let set = LineChartDataSet(entries: chartDataEntries,
label: HEALTH_TABLE.allCases[dataSourceSelected].info.name)
set.mode = .linear // cubic line effect (smoother)
set.colors = [HEALTH_TABLE.allCases[dataSourceSelected].info.chartColor]
set.setCircleColor(.black)
set.lineWidth = 1.5
set.circleRadius = 3
set.drawCircleHoleEnabled = false
set.drawCirclesEnabled = true
set.drawHorizontalHighlightIndicatorEnabled = true
lineChartData?.addDataSet(set)
}
chartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: xAxisDates)
chartView.xAxis.granularity = 1
chartView.xAxis.axisMinLabels = 4
chartView.xAxis.axisMaxLabels = 6
DispatchQueue.main.async {
self.chartView.data = self.lineChartData
}
}