I have the following code:
class ChartSeriesRow: ObservableObject {
var id = UUID()
var chartCategory: String
struct ChartSeriesData {
var chartEntry: [ChartData]
}
var chartSeries : ChartSeriesData
struct ChartData: Codable, Identifiable, Hashable {
var id = UUID()
let chartMonth: String
let chartSales: String
}
init() {
chartCategory = ""
chartSeries = ChartSeriesData(chartEntry: [ChartData(chartMonth: "01", chartSales: "10.0") ] )
}
}
How do I populate ChartSeriesData? I thought I could just add the following: However coding this way there is no append method.
extension ChartSeriesRow {
func addRow(chartRow: ChartSeriesData){
ChartSeriesRow.ChartSeriesData.chartEntry.append(contentsOf: chartRow)
}
}
You have to append to the instance, not the class. This should work:
extension ChartSeriesRow {
func addRow(chartRow: ChartData){
chartSeries.chartEntry.append(chartRow)
}
}
You use as follows:
let aChart = ChartSeriesRow()
let newRow = ChartSeriesRow.ChartData(chartMonth: "02", chartSales: "20.0")
aChart.addRow(chartRow: newRow)
print(aChart.chartSeries)
And get (in playground) (I edited with LF to make it more readable):
- ChartSeriesData(chartEntry: [
- __lldb_expr_1.ChartSeriesRow.ChartData(id: D69D70AF-A23C-44CA-9A7B-718B41ACC9F9, chartMonth: "01", chartSales: "10.0"),
- __lldb_expr_1.ChartSeriesRow.ChartData(id: 5BB0191C-DCCC-49C0-8FD5-B7BFF12B16AC, chartMonth: "02", chartSales: "20.0")
- ])