SwiftUI Charts - Plotting Date against Time (make DateComponents conform to Plottable)

431 Views Asked by At

I want to plot a date against a time, extracted from the same date: item.sunrise (ISO 8601). The compiler rejects the code below stating: Initializer init(x:y:) requires that DateComponents conform to Plottable.

        Chart{
            ForEach(sunriseSunsetDates) {item in
                LineMark(
                    x: .value("Date", calendar.dateComponents([.year, .month, .day], from: item.sunrise)),
                    y: .value("Time", calendar.dateComponents([.hour, .minute, .second], from: item.sunrise))
                )
                .foregroundStyle(.blue.gradient)
                .interpolationMethod(.catmullRom)
            }
        }

Can this be done or do I need to rewrite this in a different format?

1

There are 1 best solutions below

1
Ashley Mills On BEST ANSWER

To plot Dates, you can use the value func that takes a Date and Calendar.Component as parameters:

Chart{
    ForEach(sunriseSunsetDates) {item in
        LineMark(
            x: .value("Date", item.sunrise, unit: .day),
            y: .value("Time", item.sunrise, unit: .minute)
        )
    }
}