How to populate an array within a Class Instance?

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)
    }
}
Answered by Claude31 in 734848022

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")
  • ])
Accepted Answer

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")
  • ])

Thanks again Claude, you have been very helpful. I think I am finally understanding to store data you need an instance of an object.

How to populate an array within a Class Instance?
 
 
Q