I'm curious, does anyone know how to use the data/collection versions of charts introduced in iOS 18? Apple clearly shows in their documentation how to use the plotting versions that take a function
argument to compute their y-value, but I'm not sure how to use the versions where we supply collections as a data source.
In particular, it's unclear what form the data should take. The documentation is silent in this regard.
I'm curious, does anyone know how to use the data/collection versions of charts introduced in iOS 18? Apple clearly shows in their documentation how to use the plotting versions that take a function
argument to compute their y-value, but I'm not sure how to use the versions where we supply collections as a data source.
In particular, it's unclear what form the data should take. The documentation is silent in this regard.
Here's a minimal example:
struct PlotPoint {
let x: Double
let y: Double
}
// populate an array with the data we want to plot
let plotData: [PlotPoint] = stride(from: -3, to: 3.01, by: 0.5).map { x in
PlotPoint(x: x, y: cos(x))
}
struct LinePlotView: View {
var body: some View {
if #available(iOS 18.0, *) {
Chart {
// function version
LinePlot(x: "x", y: "y") { sin($0) }
.foregroundStyle(by: .value("expression", "y=sin(x)"))
// data version
LinePlot(plotData,
x: .value("x", \.x),
y: .value("y", \.y))
.foregroundStyle(by: .value("expression", "y=cos(x)"))
}
.chartXScale(domain: -3 ... 3)
.chartYScale(domain: -1.5 ... 1.5)
.padding()
} else {
Text("This type of chart is not available on iOS < 18")
}
}
}
plotData
is an Array
of PlotPoint
, in this case, as that's the most sensible Collection type for a LinePlot.
Unlike what I initially inferred from the docs, it looks like PlotPoint
does not need to be Identifiable
.
Also, so far as the visual output is concerned in this case, the first values (ie the labelKey
) given to the .value(_:_)
function seem to not matter. The important part is to supply the correct KeyPath
to the relevant part (x or y value) in the data structure.
This is what the output looks like: