Search code examples
swiftuiios16swiftui-charts

How do I print out the data within this struct?


Is this the place to ask for clarification on previously written lines of code? I apologize if not. I'm trying to understand some Swift code for using LineCharts. Code was written for line charts using iOS16's Swift Charts. My understanding is this code will create a list of dates and numbers to plot. But how do I call it and print out the values? Having no luck printing out data with either playground or within SwiftUI.

I'd like to somehow print out the array of data (days and numbers) that were generated before attempting to plot them.

struct HeartRate: Hashable {
  var day: String
  var value: Int = .random(in: 60..<150)
}

extension HeartRate {
  static var data: [HeartRate] {
    let calendar = Calendar(identifier: .gregorian)
    let days = calendar.shortWeekdaySymbols

    return days.map { day in
      HeartRate(day: day)
    }
  }
}

struct NewLineChartView: View {
  var dataPoints: [HeartRate]

  var body: some View {
    Chart(dataPoints, id: \.self) { rate in
      LineMark(x: .value("Day", rate.day),
               y: .value("Heart rate", rate.value))
      .foregroundStyle(.red)
      .symbol(Circle().strokeBorder(lineWidth: 1.5))
    }
  }
}

Solution

  • Do you want to print to the console? If so, you could capture and print the values(result) before charting the same values:

    extension HeartRate {
        static var data: [HeartRate] {
            let calendar = Calendar(identifier: .gregorian)
            let days = calendar.shortWeekdaySymbols
            
            let result = days.map { day in
                HeartRate(day: day)
            }
            
            print(result)
            return result
        }
    }