skip to content

Swift Charts

Swift Charts builds a chart from marks such as BarMark, LineMark and SectorMark over your data, with axes, scales and selection. It is the idiomatic way to plot data in SwiftUI with no extra library.

on this pageshow

explore

questions

6

In Swift Charts, how do you plot a week of daily step counts from an array of structs as a bar chart?

level: juniorimportance: must knowfreq 55%

answer

  1. a view built from marks
  2. Chart behaves like ForEach
  3. Identifiable or an id key path
  4. .value(label, value) per axis
  5. unit: .day for a Date

basics

~20 s

Pass the array to Chart and return one BarMark per element, giving x and y as PlottableValues built with .value("Day", entry.day, unit: .day) and .value("Steps", entry.steps); the elements must be Identifiable or you supply id:.

solid answer

~40 s

A `Chart` is a SwiftUI view whose content is marks. `Chart(week) { entry in BarMark(x: .value("Day", entry.day, unit: .day), y: .value("Steps", entry.steps)) }` creates one bar per element, much as `ForEach` creates one view per element, so the element type must be `Identifiable` or you call `Chart(week, id: \.day)`. Each `.value(_:_:)` builds a `PlottableValue`: a label naming the dimension plus a value whose type conforms to `Plottable`. The value's type decides the scale: `String` gives categories, `Int` or `Double` a quantity, `Date` a time axis. For a `Date`, `unit: .day` treats each value as a whole day, so each bar fills its day's slot. When you need marks that do not repeat per element, such as a goal line, write `Chart { ForEach(week) { ... }; RuleMark(...) }` instead.

code

swift · 23 lines
swift
import SwiftUI
import Charts

struct DailySteps: Identifiable {
    let id = UUID()
    let day: Date
    let steps: Int
}

struct WeeklyStepsChart: View {
    let week: [DailySteps]

    var body: some View {
        Chart(week) { entry in
            BarMark(
                x: .value("Day", entry.day, unit: .day),
                y: .value("Steps", entry.steps)
            )
        }
        .chartYAxisLabel("Steps")
        .frame(height: 220)
    }
}

go deeper

for a junior

Recall the shape: Chart over the array, one BarMark per element, x and y as .value(label, value). Know that elements must be Identifiable or given an id key path.

for a middle

Explain what PlottableValue carries, how the Swift type of the value picks a categorical, numeric or date scale, and why unit: .day matters for daily totals.

for a senior

Show you can spot data bugs that surface as chart bugs, such as duplicate days stacking silently, and choose between the data initializer and a builder with ForEach.

for a principal

Frame Swift Charts as the default for in-app charts on iOS 16 and later, and know when a chart's data model deserves its own aggregation layer before plotting.

## What a chart is made of Swift Charts is Apple's declarative charting framework, shipped with **iOS 16**. A `Chart` is an ordinary SwiftUI view, so it sits in a `VStack`, takes `.frame(height:)` and re-renders when its data changes. What it draws is described by **marks**: `BarMark`, `LineMark`, `AreaMark`, `PointMark`, `RuleMark` and `RectangleMark` from the first release, and `SectorMark` from iOS 17. Each mark maps properties of one data element to visual channels such as x position, y position and colour. A bar chart of a week of steps therefore needs three things: - a data type, for example `struct DailySteps { let day: Date; let steps: Int }`; - a `Chart` that walks the array; - one `BarMark` per element, saying which property goes on x and which on y. ## Feeding data: `Chart(data)` versus `Chart { ForEach }` `Chart` has three initializers. `Chart(_:content:)` takes a `RandomAccessCollection` whose elements are `Identifiable` and calls the closure once per element. Apple's documentation describes it as behaving "a lot like a SwiftUI ForEach", and its declaration builds exactly that: the content type is a `ForEach`. `Chart(_:id:content:)` does the same for elements that are not `Identifiable`, taking a key path such as `\.day`. Pass a non-`Identifiable` array to the first form and the compiler stops with "initializer 'init(_:content:)' requires that 'DailySteps' conform to 'Identifiable'". The third form, `Chart(content:)`, takes a builder and no data. Inside it you write your own `ForEach` loops plus any marks that should appear once: ```swift Chart { ForEach(week) { entry in BarMark(x: .value("Day", entry.day, unit: .day), y: .value("Steps", entry.steps)) } RuleMark(y: .value("Goal", 10_000)) } ``` Use the data form when every mark comes from the same collection, and the builder form when you combine several collections or add constant marks. ## `PlottableValue` and the `.value(_:_:)` labels Every mark parameter (`x:`, `y:`, `angle:`, `series:`) and every encoding modifier (`foregroundStyle(by:)`, `symbol(by:)`) takes a `PlottableValue`. You build one with the static `.value(_:_:)` method: the first argument is a **label** (a `LocalizedStringKey`, a `String`, a `Text` or a `LocalizedStringResource`), the second the **value**. The label names the data dimension. Swift Charts uses it when it describes that dimension, and per mark you can override what VoiceOver reads with `accessibilityLabel(_:)` and `accessibilityValue(_:)`. Visible axis titles are a separate matter: add them with `chartXAxisLabel(_:)` and `chartYAxisLabel(_:)`. The value must conform to `Plottable`. The type you pass decides what kind of scale Charts builds: | Value type | Kind of data | Typical axis | |---|---|---| | `String` | categorical | one slot per distinct value | | `Int`, `Double` | quantitative | a numeric range | | `Date` | temporal | a time axis | | an enum with a `String` raw value that adopts `Plottable` | categorical | the raw values, used as localized keys | A custom type can adopt `Plottable` by mapping itself to one of the primitive plottable types through `primitivePlottable` and `init?(primitivePlottable:)`. ## Dates and the `unit` parameter A step total belongs to a whole day, not to the instant stored in the `Date`. The overload `.value(_:_:unit:calendar:)` says so: `.value("Day", entry.day, unit: .day)` treats each date as the interval of its day, so a bar fills that day's slot on the time axis. Pass `.hour`, `.weekOfYear` or `.month` for other bin sizes. ## When several bars land on the same x If two elements map to the same location, `BarMark` stacks them; the documentation states this outright. With one entry per day you get one bar per day. If the array accidentally holds two rows for Monday, Monday's bar is the sum of both, drawn as one column in one colour. That is a data bug that looks like a chart bug. ## Same data, other marks Because the encoding lives in the `.value` arguments, the mark type decides how the same week is drawn, and swapping it is a one-word change: - `BarMark(x:y:)` draws one bar per element; - `LineMark(x:y:)` joins the days into a line; - `PointMark(x:y:)` draws one symbol per day; - `AreaMark(x:y:)` fills the region under the line. Marks compose inside one chart, so a `LineMark` and a `PointMark` over the same values give a line with a dot on each day. Orientation follows the value types as well: put the step count on `x` and a `String` day name on `y`, and `BarMark` draws horizontal bars. Which form suits the data is a visualization-design decision; the API point is that the mark, not a chart-type setting, decides the drawing. ## Common mistakes 1. Passing a non-`Identifiable` array to `Chart(_:content:)` instead of adding `id:` or adopting `Identifiable`. 2. Plotting a `Date` without `unit:` when each value represents a whole day. 3. Converting dates to `String` to "fix" the axis, which turns time into plain categories and drops the time scale. 4. Expecting `.value`'s label to appear as an axis title without `chartYAxisLabel(_:)`. 5. Putting a one-off mark inside `Chart(week) { entry in ... }`, where it is repeated once per element.

  • In Swift Charts, what happens if the step array holds two entries for the same day?
    `BarMark` stacks marks that map to the same location, so that day shows one column whose height is the sum of both entries. Without `foregroundStyle(by:)` both segments share one colour and the chart looks like a single tall bar, so the duplicate goes unnoticed. Aggregate per day before plotting, or encode the second dimension with `foregroundStyle(by:)` when the split is intended.
  • In Swift Charts, how do you plot an enum such as an activity kind as a category?
    Give the enum a `String` raw value and declare conformance to `Plottable`; Swift Charts provides the implementation for `String`-backed raw-representable types. The raw values are then used as localized string keys wherever the chart shows the category as text, for example on an axis.

  • Swift Charts needs a third-party package to draw a bar chart
  • Chart(data) works with any array, Identifiable or not
  • Converting dates to strings is the right way to get a day axis
  • The .value label automatically becomes the visible axis title
  • BarMark draws two bars side by side when they share an x value
open as a page

In Swift Charts, what does foregroundStyle(by:) do that foregroundStyle(_:) does not, for steps split into walking and running?

level: middleimportance: should knowfreq 45%

basics

~10 s

foregroundStyle(by:) maps a data value to a colour through a scale, so each activity gets its own style, a legend appears and LineMarks split into series; foregroundStyle(_:) paints every mark one fixed ShapeStyle.

open as a page

In Swift Charts, how do you draw a 10,000-step goal line across a weekly bar chart and stop the y-axis rescaling every week?

level: middleimportance: should knowfreq 40%

basics

~10 s

Add one RuleMark(y: .value("Goal", 10_000)) beside a ForEach of BarMarks inside Chart { }, label it with annotation, and fix the axis with chartYScale(domain: 0...15_000) so it stops following each week's data.

open as a page

In Swift Charts on iOS 17 and later, how do you let a user scrub a heart-rate line chart with a finger and mark the selected sample?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Bind chartXSelection(value:) to an optional Date; the chart writes the x value under the finger, you look up the nearest sample, and an if let in the Chart builder draws a RuleMark(x:) with an annotation for the reading.

open as a page

In Swift Charts, how do you show a year of daily step totals as a horizontally scrolling chart that opens on the latest week?

level: seniorimportance: nice to knowfreq 25%

basics

~10 s

From iOS 17, add chartScrollableAxes(.horizontal), set chartXVisibleDomain(length:) to one week in seconds, open with chartScrollPosition(initialX:) at the latest week's start, and snap with chartScrollTargetBehavior(.valueAligned(matching:)).

open as a page

In Swift Charts on iOS 17 and later, how do you build a spending donut by category with SectorMark, and find which slice the user touched?

level: seniorimportance: nice to knowfreq 30%

basics

~10 s

Plot SectorMark(angle: .value("Amount", amount), innerRadius: .ratio(0.618)) per category with foregroundStyle(by:); chartAngleSelection(value:) returns a value along the running total, which you map back to a category by summing amounts in data order.

open as a page