Swift & SwiftUI course › Session 8
Swift Charts
Draw bar, line, point, area, rule, rectangle and sector charts with Swift Charts, customise axes, colours and legends, add selection and scrolling, and prepare the data in plain Swift.
About 50 minutes · covers All mark types, customization and interaction
Open the interactive lesson (live previews, quizzes) →What you'll learn
- Build a
Chartfrom an array ofIdentifiablestructs using.value(_:_:) - Pick the right mark for the question and combine marks in one chart
- Customise colours, axes, scales, legends and annotations
- Add selection (
chartXSelection,chartAngleSelection) and scrolling, and know they need iOS 17 - Group, sort, average and accumulate data in plain Swift before it reaches the chart
Contents
- What Swift Charts is
- Data for a chart
- BarMark
- LineMark, PointMark and AreaMark
- RuleMark, RectangleMark and SectorMark
- Which mark for which question
- Customising a chart
- Selection and scrolling
- Preparing chart data in plain Swift
- Bug hunt: charts that compile but mislead
What Swift Charts is
Swift Charts is Apple's framework for drawing charts declaratively in SwiftUI. You describe marks (bars, lines, points…) for your data; Charts works out the axes, scales, colours, legend and accessibility for you.
Add import Charts next to import SwiftUI. A Chart is an ordinary SwiftUI view: you can put it in a VStack, give it a .frame(height:), and drive it from @State.
import SwiftUI
import Charts
struct SubjectHours: Identifiable {
let subject: String
let hours: Double
var id: String { subject }
}
struct HoursChart: View {
let data = [
SubjectHours(subject: "Maths", hours: 8.5),
SubjectHours(subject: "Physics", hours: 4.5),
SubjectHours(subject: "English", hours: 2.5),
]
var body: some View {
Chart(data) { item in
BarMark(
x: .value("Subject", item.subject),
y: .value("Hours", item.hours)
)
}
.frame(height: 220)
}
}Chart(data) { item in ... }loops over the data, likeListorForEach. The data must beIdentifiable, or you passid:.- Each mark is one visual element: here one bar per subject.
.value("Subject", item.subject)is a PlottableValue: a label plus a value. The label describes the data (VoiceOver reads it); it is not drawn on the axis.- A
Stringon an axis gives categories; a number gives a continuous scale; aDategives a time scale.
Availability
| API | Minimum iOS |
|---|---|
Chart, BarMark, LineMark, PointMark, AreaMark, RuleMark, RectangleMark | iOS 16 |
Axes, scales, legends, annotation, chartOverlay + ChartProxy | iOS 16 |
SectorMark (pie and donut) | iOS 17 |
chartXSelection, chartYSelection, chartAngleSelection | iOS 17 |
chartScrollableAxes, chartXVisibleDomain, chartScrollPosition | iOS 17 |
The demo draws the same data with each mark. Notice that only the mark type changes; the data and the .value calls stay the same. That is the core idea of Swift Charts.
Data for a chart
Charts don't read files or databases. They draw an array you prepare. Model each row as a struct, and make it Identifiable so Chart can tell the rows apart.
// 1. Identifiable with a stored id
struct Score: Identifiable {
let id = UUID()
let student: String
let marks: Int
}
Chart(scores) { s in
BarMark(x: .value("Student", s.student), y: .value("Marks", s.marks))
}
// 2. Not Identifiable: say which property is unique
Chart(scores, id: \.student) { s in
BarMark(x: .value("Student", s.student), y: .value("Marks", s.marks))
}
// 3. A plain array of strings: the string is its own id
Chart(subjects, id: \.self) { name in
BarMark(x: .value("Subject", name), y: .value("Count", name.count))
}
// 4. ForEach inside Chart: needed when you mix data marks with other marks
Chart {
ForEach(days.indices, id: \.self) { i in
LineMark(x: .value("Day", days[i]), y: .value("Hours", hours[i]))
}
RuleMark(y: .value("Target", 3))
}Prepare the data in plain Swift first. This part runs in the Playground (it uses a computed id instead of UUID(), which needs Foundation):
struct SubjectHours: Identifiable {
let subject: String
let hours: Double
var id: String { subject }
}
let data = [
SubjectHours(subject: "Maths", hours: 8.5),
SubjectHours(subject: "Physics", hours: 4.5),
SubjectHours(subject: "English", hours: 2.5),
]
print(data.count)
print(data.map { $0.id })
print(data[0].subject, data[0].hours)Output
3
["Maths", "Physics", "English"]
Maths 8.5Plottable types
| Swift type | Axis kind | Example |
|---|---|---|
String | Categorical: one slot per distinct value | .value("Subject", "Maths") |
Int, Double, Float | Quantitative: a continuous number line | .value("Hours", 2.5) |
Date | Temporal: a time line | .value("Day", date, unit: .day) |
Only Plottable types can go in .value. For an enum, plot its rawValue string. A custom struct can't be plotted directly: plot one of its properties.
struct SubjectHours {
let subject: String
let hours: Double
}
let rows = [SubjectHours(subject: "Maths", hours: 2)]
let first: SubjectHours = rows.firstfirst returns an optional (SubjectHours?) because the array might be empty. Unwrap it with if let, guard let or ??. The same applies to dictionary lookups when you build chart data.
Quick charts from tuples
For a throwaway chart you may not want a struct at all: an array of tuples such as ("Mon", 3) is enough. But a tuple can't conform to any protocol, so it can't be Identifiable (or Hashable). You must tell Chart or ForEach which element is the id, with a key path to a tuple element: \.0 is the first element.
import SwiftUI
import Charts
struct StepsChart: View {
let steps: [(day: String, count: Int)] = [
("Mon", 4200), ("Tue", 6100), ("Wed", 3900), ("Thu", 7400),
]
var body: some View {
// Form 1: the data goes to Chart, with an explicit id
Chart(steps, id: \.day) { item in
BarMark(x: .value("Day", item.day), y: .value("Steps", item.count))
}
// Form 2: ForEach inside Chart, needed when you add other marks
Chart {
ForEach(steps, id: \.0) { item in
LineMark(x: .value("Day", item.0), y: .value("Steps", item.1))
}
RuleMark(y: .value("Goal", 5000))
}
}
}Chart(steps) { ... }withoutid:is a compile error: the tuple isn'tIdentifiable.- The id must be unique: with two "Mon" rows,
id: \.0gives two marks the same identity. Total per day first, or switch to a struct with its own id. - Tuples are fine for a demo or an exam answer. For real data, a struct is clearer and can be
Identifiable,Codableand tested.
let steps: [(day: String, count: Int)] = [("Mon", 4200), ("Tue", 6100), ("Mon", 900)]
print(steps[0].day, steps[0].0, steps[1].count)
var totals: [String: Int] = [:]
for item in steps { totals[item.day, default: 0] += item.count }
let unique = totals.sorted { $0.key < $1.key }.map { (day: $0.key, count: $0.value) }
for item in unique { print(item.day, item.count) }Output
Mon Mon 6100
Mon 5100
Tue 6100BarMark
BarMark compares values across categories. Which axis gets the category decides the direction.
// Vertical bars: category on x
BarMark(x: .value("Subject", item.subject), y: .value("Hours", item.hours))
// Horizontal bars: swap them, category on y
BarMark(x: .value("Hours", item.hours), y: .value("Subject", item.subject))Stacked, grouped and normalised bars
struct ExamScore: Identifiable {
let id = UUID()
let subject: String
let exam: String // "Mid-term" or "Final"
let marks: Int
}
// Stacked (the default): bars that share an x value stack on top of each other
Chart(scores) { s in
BarMark(x: .value("Subject", s.subject), y: .value("Marks", s.marks))
.foregroundStyle(by: .value("Exam", s.exam))
}
// Grouped: side by side instead of stacked
Chart(scores) { s in
BarMark(x: .value("Subject", s.subject), y: .value("Marks", s.marks))
.foregroundStyle(by: .value("Exam", s.exam))
.position(by: .value("Exam", s.exam))
}
// 100% stacked: each bar is scaled to the full height
Chart(scores) { s in
BarMark(x: .value("Subject", s.subject), y: .value("Marks", s.marks), stacking: .normalized)
.foregroundStyle(by: .value("Exam", s.exam))
}Range bars
// A floating bar from low to high (temperature range, min/max marks)
BarMark(
x: .value("Day", d.day),
yStart: .value("Lowest", d.low),
yEnd: .value("Highest", d.high)
)
// A timeline (Gantt) bar: horizontal, from start to end
BarMark(
xStart: .value("Start", task.startHour),
xEnd: .value("End", task.endHour),
y: .value("Task", task.name)
)| You want | Write |
|---|---|
| Vertical bars | BarMark(x: category, y: number) |
| Horizontal bars | BarMark(x: number, y: category) |
| Stacked by series | .foregroundStyle(by: .value("Series", s)) |
| Grouped side by side | add .position(by: .value("Series", s)) |
| 100% stacked | BarMark(..., stacking: .normalized) |
| Floating range | BarMark(x:, yStart:, yEnd:) |
| Rounded bars | .cornerRadius(6) |
Switching stacked and grouped with if
A chart's content closure is a result builder, like a view's body, so it accepts if and if/else. Use it to let the user flip between stacked and grouped bars:
struct ExamChart: View {
let scores: [ExamScore]
@State private var grouped = false
var body: some View {
VStack {
Picker("Layout", selection: $grouped) {
Text("Stacked").tag(false)
Text("Grouped").tag(true)
}
.pickerStyle(.segmented)
Chart(scores) { s in
if grouped {
BarMark(x: .value("Subject", s.subject), y: .value("Marks", s.marks))
.foregroundStyle(by: .value("Exam", s.exam))
.position(by: .value("Exam", s.exam))
} else {
BarMark(x: .value("Subject", s.subject), y: .value("Marks", s.marks))
.foregroundStyle(by: .value("Exam", s.exam))
}
}
.animation(.easeInOut, value: grouped)
}
}
}The data side: bars usually show totals per category, so you add up the rows first, then sort for bar order.
let subjects = ["Maths", "Physics", "Maths", "English", "Physics", "Maths"]
let hours = [2.0, 1.0, 1.5, 1.0, 2.0, 2.5]
var totals: [String: Double] = [:]
for i in subjects.indices {
totals[subjects[i], default: 0.0] += hours[i]
}
let bars = totals.sorted { $0.value > $1.value }
for bar in bars {
print(bar.key, bar.value)
}Output
Maths 6.0
Physics 3.0
English 1.0LineMark, PointMark and AreaMark
LineMark: trends
LineMark joins points in x order. Use it for a trend over time (days, weeks, months).
struct WeekScore: Identifiable {
let id = UUID()
let student: String
let week: Int
let marks: Int
}
// One line per student, coloured, with a legend
Chart(scores) { s in
LineMark(x: .value("Week", s.week), y: .value("Marks", s.marks))
.foregroundStyle(by: .value("Student", s.student))
.interpolationMethod(.catmullRom)
}
// One line per student, all the same colour
Chart(scores) { s in
LineMark(
x: .value("Week", s.week),
y: .value("Marks", s.marks),
series: .value("Student", s.student)
)
}| interpolationMethod | Shape |
|---|---|
.linear (default) | Straight segments between points |
.catmullRom | Smooth curve through every point (can overshoot) |
.monotone | Smooth curve that never overshoots between points |
.stepStart, .stepCenter, .stepEnd | Steps: the value jumps, like a price or level change |
.cardinal | Smooth curve with adjustable tension |
PointMark: scatter plots
PointMark draws a dot per row. With two numbers on the axes it shows correlation: do more study hours go with higher marks?
Chart(students) { s in
PointMark(
x: .value("Study hours", s.hours),
y: .value("Marks", s.marks)
)
.foregroundStyle(by: .value("Year", s.year))
.symbol(by: .value("Year", s.year)) // different shape per year
.symbolSize(80)
}AreaMark: volume over time
// Stacked areas: each subject's hours stack to the weekly total
Chart(logs) { log in
AreaMark(
x: .value("Week", log.week),
y: .value("Hours", log.hours)
)
.foregroundStyle(by: .value("Subject", log.subject))
}
// A band between two values
AreaMark(
x: .value("Week", p.week),
yStart: .value("Lowest", p.low),
yEnd: .value("Highest", p.high)
)
.opacity(0.3)A cumulative line (total so far) needs a running total. Compute it before charting:
let daily = [3.0, 2.5, 3.0, 2.5]
var running = 0.0
var cumulative: [Double] = []
for h in daily {
running += h
cumulative.append(running)
}
print(cumulative)Show the answer
[3.0, 5.5, 8.5, 11.0]RuleMark, RectangleMark and SectorMark
RuleMark: thresholds and averages
RuleMark draws a straight line across the plot. Give it only y: for a horizontal line (a target or average), or only x: for a vertical line (a date or a selection).
Chart {
ForEach(days) { d in
BarMark(x: .value("Day", d.day), y: .value("Hours", d.hours))
}
RuleMark(y: .value("Average", average))
.foregroundStyle(.red)
.lineStyle(StrokeStyle(lineWidth: 2, dash: [5, 3]))
.annotation(position: .top, alignment: .leading) {
Text("Average")
.font(.caption)
}
}let hours = [3.0, 2.5, 3.0, 2.5, 2.5, 6.5, 0.0]
let total = hours.reduce(0.0, +)
let average = total / Double(hours.count)
print(total)
print(average)
print((average * 100).rounded() / 100)Output
20.0
2.857142857142857
2.86RectangleMark: heat maps
struct Cell: Identifiable {
let id = UUID()
let day: String // "Mon" ... "Sun"
let slot: String // "Morning", "Afternoon", "Evening"
let minutes: Int
}
Chart(cells) { c in
RectangleMark(
x: .value("Day", c.day),
y: .value("Slot", c.slot)
)
.foregroundStyle(by: .value("Minutes", c.minutes))
}With categories on both axes, each RectangleMark fills one cell of a grid. Colouring by a number gives a gradient, so darker cells mean more minutes.
SectorMark: pie and donut (iOS 17)
Chart(bySubject) { item in
SectorMark(
angle: .value("Hours", item.hours),
innerRadius: .ratio(0.6), // leave out for a full pie
angularInset: 2 // gap between slices, in points
)
.cornerRadius(4)
.foregroundStyle(by: .value("Subject", item.subject))
}
.frame(height: 240)angle:is the size of the slice. Charts adds up all the values and gives each slice its share of 360 degrees. You don't have to pass percentages.innerRadius: .ratio(0.6)cuts a hole 60% of the radius: a donut..inset(20)and.fixed(50)are the other options.angularInset:separates the slices;.cornerRadiusrounds them.- A sector chart has no axes. The legend from
foregroundStyle(by:)says which colour is which.
You still compute percentages when you want to label the slices:
let subjects = ["Maths", "Chemistry", "Physics", "English"]
let hours = [8.5, 4.5, 4.5, 2.5]
let total = hours.reduce(0.0, +)
for i in subjects.indices {
let percent = hours[i] / total * 100
print("\(subjects[i]): \(percent)%")
}Output
Maths: 42.5%
Chemistry: 22.5%
Physics: 22.5%
English: 12.5%Try “RuleMark, RectangleMark and SectorMark” with live code →
Which mark for which question
| The question | Mark | Example |
|---|---|---|
| Compare values across categories | BarMark | Hours per subject |
| Trend over time | LineMark | Hours per day this week |
| Correlation between two numbers | PointMark | Study hours vs marks |
| Part of a whole | SectorMark | Share of time per subject |
| A threshold, target or average | RuleMark | Daily target of 3 hours |
| Volume or cumulative amount over time | AreaMark | Hours per subject, stacked per week |
| A value for each cell of a matrix | RectangleMark | Minutes per day and time slot |
| A range (min to max) | BarMark with yStart/yEnd | Lowest and highest marks per test |
Combining marks
Put several marks in the same Chart and they share the axes. Use Chart { ForEach(...) { ... } } when the marks come from different data, or several marks inside one Chart(data) closure when they come from the same row.
// Line with a dot on every point: two marks per row
Chart(byDay) { d in
LineMark(x: .value("Day", d.day), y: .value("Hours", d.hours))
PointMark(x: .value("Day", d.day), y: .value("Hours", d.hours))
}
// Bars plus one average rule: the rule isn't per row, so use ForEach
Chart {
ForEach(byDay) { d in
BarMark(x: .value("Day", d.day), y: .value("Hours", d.hours))
}
RuleMark(y: .value("Average", average))
}Customising a chart
Colours
// One fixed colour for every bar: no legend
BarMark(x: .value("Subject", s.subject), y: .value("Hours", s.hours))
.foregroundStyle(.teal)
// Colour by category: automatic palette and a legend
.foregroundStyle(by: .value("Subject", s.subject))
// Choose the colour for each category
Chart(data) { s in
BarMark(x: .value("Subject", s.subject), y: .value("Hours", s.hours))
.foregroundStyle(by: .value("Subject", s.subject))
}
.chartForegroundStyleScale([
"Maths": Color.blue,
"Physics": Color.orange,
"English": Color.purple,
])| Modifier | Applies to | Effect |
|---|---|---|
.foregroundStyle(.red) | A mark | Same colour for every mark, no legend |
.foregroundStyle(by: .value(...)) | A mark | Colour per value, automatic legend |
.chartForegroundStyleScale([...]) | The Chart | Which colour each value gets |
Axes and scale
Chart(byDay) { d in
BarMark(x: .value("Day", d.date, unit: .day), y: .value("Hours", d.hours))
}
.chartXAxis {
AxisMarks(values: .stride(by: .day)) { value in
AxisGridLine()
AxisTick()
AxisValueLabel(format: .dateTime.weekday(.abbreviated)) // Mon, Tue...
}
}
.chartYAxis {
AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { value in
AxisGridLine()
AxisValueLabel {
if let hours = value.as(Double.self) {
Text("\(hours, format: .number) h")
}
}
}
}
.chartYScale(domain: 0...8)
.chartXAxisLabel("Day")
.chartYAxisLabel("Hours")
.frame(height: 240)AxisMarksdescribes the marks on one axis:AxisGridLine(line across the plot),AxisTick(small tick) andAxisValueLabel(the text).values:picks where they go:.automatic(desiredCount:),.stride(by: .day)for dates, or an explicit array..chartXAxis(.hidden)removes an axis completely..chartYScale(domain: 0...8)fixes the range, so the chart doesn't jump when the data changes..value("Day", date, unit: .day)groups dates by day, so a bar is one day wide. Use.monthfor monthly bars.
Legend, annotations and accessibility
Chart(bySubject) { s in
BarMark(x: .value("Subject", s.subject), y: .value("Hours", s.hours))
.foregroundStyle(by: .value("Subject", s.subject))
.annotation(position: .top) {
Text("\(s.hours, format: .number)")
.font(.caption)
}
.accessibilityLabel(s.subject)
.accessibilityValue("\(s.hours, format: .number) hours")
}
.chartLegend(position: .bottom) // or .chartLegend(.hidden)Charts are accessible by default: VoiceOver reads each mark using the .value labels, and offers an Audio Graph that plays the data as tones. accessibilityLabel and accessibilityValue replace the default text with something clearer.
Annotations often mark the maximum. Find it in plain Swift:
struct DayHours {
let day: String
let hours: Double
}
let week = [
DayHours(day: "Mon", hours: 3),
DayHours(day: "Tue", hours: 2.5),
DayHours(day: "Sat", hours: 6.5),
DayHours(day: "Sun", hours: 0),
]
if let best = week.max(by: { $0.hours < $1.hours }) {
print("Best:", best.day, best.hours)
}
print(week.map { $0.hours }.max()!)Output
Best: Sat 6.5
6.5Selection and scrolling
chartXSelection (iOS 17)
chartXSelection(value:) binds to an optional @State of the x axis's type. When the user touches or drags on the chart, Charts sets it to the x value under the finger; when they let go, it becomes nil. You draw the highlight yourself, usually a RuleMark at the selected value.
struct WeekView: View {
let byDay: [DayTotal] // day: String, hours: Double
@State private var selectedDay: String?
var body: some View {
Chart {
ForEach(byDay) { d in
LineMark(x: .value("Day", d.day), y: .value("Hours", d.hours))
PointMark(x: .value("Day", d.day), y: .value("Hours", d.hours))
}
if let selectedDay {
RuleMark(x: .value("Day", selectedDay))
.foregroundStyle(.gray.opacity(0.4))
.annotation(position: .top) {
Text(selectedDay)
.font(.caption)
}
}
}
.chartXSelection(value: $selectedDay)
.frame(height: 220)
}
}chartAngleSelection for pie charts (iOS 17)
chartAngleSelection(value:) gives you a number on the angle scale, not the slice. With slices of 8.5, 4.5, 4.5 and 2.5 hours, the scale runs from 0 to 20. A selected value of 10 lands in the second slice. You find the slice with a running total:
let subjects = ["Maths", "Chemistry", "Physics", "English"]
let hours = [8.5, 4.5, 4.5, 2.5]
func slice(at value: Double) -> String? {
var running = 0.0
for i in subjects.indices {
running += hours[i]
if value <= running { return subjects[i] }
}
return nil
}
print(slice(at: 3) ?? "none")
print(slice(at: 10) ?? "none")
print(slice(at: 19.9) ?? "none")
print(slice(at: 25) ?? "none")Output
Maths
Chemistry
English
none@State private var selectedAngle: Double?
Chart(bySubject) { s in
SectorMark(angle: .value("Hours", s.hours), innerRadius: .ratio(0.6))
.foregroundStyle(by: .value("Subject", s.subject))
.opacity(selectedSubject == nil || selectedSubject == s.subject ? 1 : 0.4)
}
.chartAngleSelection(value: $selectedAngle)
// selectedSubject is computed from selectedAngle with the running-total search aboveScrolling (iOS 17)
Chart(last30Days) { d in
BarMark(x: .value("Day", d.date, unit: .day), y: .value("Hours", d.hours))
}
.chartScrollableAxes(.horizontal)
.chartXVisibleDomain(length: 3600 * 24 * 7) // show 7 days at a time
.chartScrollPosition(initialX: startDate)For a date axis, length: is in seconds. For a categorical axis it is the number of categories, for example chartXVisibleDomain(length: 5).
Before iOS 17: chartOverlay and ChartProxy
Chart(byDay) { d in
BarMark(x: .value("Day", d.day), y: .value("Hours", d.hours))
}
.chartOverlay { proxy in
GeometryReader { geo in
Rectangle()
.fill(.clear)
.contentShape(Rectangle())
.gesture(
DragGesture(minimumDistance: 0)
.onChanged { drag in
let origin = geo[proxy.plotAreaFrame].origin
let x = drag.location.x - origin.x
selectedDay = proxy.value(atX: x, as: String.self)
}
.onEnded { _ in selectedDay = nil }
)
}
}chartOverlayplaces a view over the chart and hands you aChartProxy.proxy.value(atX:as:)turns a screen position into a data value;proxy.position(forX:)does the reverse.plotAreaFrameis the plot rectangle. On iOS 17 it is deprecated in favour of the optionalplotFrame.- On iOS 17, prefer
chartXSelection: much less code.
Preparing chart data in plain Swift
Exams ask about the data side as often as the chart syntax: group raw rows, total them, sort them, and derive averages, percentages and running totals. All of this is plain Swift.
Grouping with Dictionary(grouping:by:)
struct StudySession {
let day: String
let subject: String
let hours: Double
}
let sessions = [
StudySession(day: "Mon", subject: "Maths", hours: 2),
StudySession(day: "Mon", subject: "Physics", hours: 1),
StudySession(day: "Tue", subject: "Maths", hours: 1),
StudySession(day: "Wed", subject: "Physics", hours: 2),
StudySession(day: "Thu", subject: "Maths", hours: 2.5),
]
let grouped = Dictionary(grouping: sessions, by: { $0.subject })
print(grouped.keys.sorted())
print(grouped["Maths"]!.count)
let totals = grouped.mapValues { rows in rows.reduce(0.0) { $0 + $1.hours } }
for subject in totals.keys.sorted() {
print(subject, totals[subject]!)
}Output
["Maths", "Physics"]
3
Maths 5.5
Physics 3.0| Step | Code | Result type |
|---|---|---|
| Group rows by a key | Dictionary(grouping: rows, by: { $0.subject }) | [String: [StudySession]] |
| Total each group | .mapValues { $0.reduce(0.0) { $0 + $1.hours } } | [String: Double] |
| Same total in one loop | totals[s.subject, default: 0.0] += s.hours | [String: Double] |
| Order for the chart | .sorted { $0.value > $1.value } | [(key: String, value: Double)] |
Sorting with a tie-breaker
let totals = ["Physics": 4.5, "Maths": 8.5, "Chemistry": 4.5, "English": 2.5]
let rows = totals.sorted {
$0.value != $1.value ? $0.value > $1.value : $0.key < $1.key
}
print(rows.map { $0.key })Show the answer
["Maths", "Chemistry", "Physics", "English"]Without the tie-breaker, Physics and Chemistry (both 4.5) could swap places between runs, because the dictionary's order isn't fixed. The tie-breaker makes the bar order stable.
Filling in missing categories
A line over the week needs all 7 days, including days with no study. Map over the list of days, not over the data:
let days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
let logged = ["Mon": 3.0, "Wed": 2.0, "Sat": 4.5]
let line = days.map { logged[$0] ?? 0.0 }
print(line)
print(line.count)Output
[3.0, 0.0, 2.0, 0.0, 0.0, 4.5, 0.0]
7var totals: [String: Double] = [:]
totals["Maths"] += 2.5totals["Maths"] is Double?, and += doesn't work on an optional. Write totals["Maths", default: 0] += 2.5.
let hours = [2, 3, 4]
let average = hours.reduce(0, +) / hours.count
let exact = Double(hours.reduce(0, +)) / Double(hours.count)
print(average, exact)Show the answer
3 3.0let hours = [1, 2]
print(hours.reduce(0, +) / hours.count)
print(Double(hours.reduce(0, +)) / Double(hours.count))Show the answer
1
1.5Bug hunt: charts that compile but mislead
This chart builds without errors, yet five things are wrong with what it shows or how it behaves. Find each one.
import SwiftUI
import Charts
struct Sale: Identifiable {
let id: Int
let month: String
let region: String
let amount: Double
}
struct SalesChart: View {
let sales: [Sale] // unsorted months
@State private var picked: String?
var average: Double {
Double(Int(sales.map { $0.amount }.reduce(0, +)) / sales.count) // [A]
}
var body: some View {
Chart {
ForEach(sales) { s in
LineMark(x: .value("Month", s.month), y: .value("Amount", s.amount)) // [B]
RuleMark(y: .value("Average", average)) // [C]
}
}
.foregroundStyle(.blue) // [D]
.chartXSelection(value: $picked)
.chartYAxisLabel("Amount")
.overlay {
if let picked { Text(picked) } // [E]
}
}
}Show the bugs
- [A] The total is converted to
Intbefore dividing, so the average is truncated and the rule sits too low. (It also divides by zero whensalesis empty.) Fix:sales.isEmpty ? 0 : sales.map { $0.amount }.reduce(0, +) / Double(sales.count). - [B] Several regions share months but there is no
foregroundStyle(by:)orseries:, so one zigzag line joins every point. Months also appear in data order, not calendar order. Fix: Add.foregroundStyle(by: .value("Region", s.region))and sort the data by month first. - [C] The
RuleMarkis inside theForEach, so one identical rule is drawn per row. Fix: Move it out of theForEach, after it, insideChart { }. - [D] A fixed
.foregroundStyle(.blue)on the whole chart colours every series the same and gives no legend. Fix: Remove it and colour by region withforegroundStyle(by:). - [E] The overlay covers the whole chart and doesn't say which value was picked or where; it also shows nothing useful about the amount. Fix: Show a
RuleMark(x:)at the picked month with an.annotationthat lists the amounts for that month.
Try “Bug hunt: charts that compile but mislead” with live code →
Exam traps
| Code or claim | What really happens |
|---|---|
Minimum iOS for Chart and BarMark | iOS 16 |
Minimum iOS for SectorMark and chartXSelection | iOS 17 |
.value("Hours", h): is the label drawn on the axis? | No. It describes the data for accessibility; use chartYAxisLabel for an axis title |
Chart(data) where the struct isn't Identifiable | Compile error: make it Identifiable or pass id: |
| Category order on the axis | Order of first appearance in the data, not alphabetical: sort the array |
BarMark(x: number, y: category) | Horizontal bars |
Bars with foregroundStyle(by:) only | Stacked, not grouped |
| Grouped bars | Add .position(by: .value(...)) |
LineMark for several students without foregroundStyle(by:) or series: | One zigzag line through every point |
.interpolationMethod(.catmullRom) vs .monotone | Both smooth; catmullRom can overshoot, monotone can't |
RuleMark(y:) vs RuleMark(x:) | Horizontal line vs vertical line |
RuleMark inside Chart(data) { } | One rule per row; put it outside the ForEach |
SectorMark(angle:) values | Raw values; Charts works out each share of the total |
| Donut vs pie | Donut sets innerRadius: .ratio(0.6) (or similar); pie leaves it out |
.foregroundStyle(.red) vs .foregroundStyle(by:) | Fixed colour, no legend vs colour per value with a legend |
Date x value without unit: | Each date is an instant: thin bars, same-day rows not combined |
chartXSelection(value: $day) where day is String | Compile error: the binding must be optional (String?) |
chartAngleSelection result | A number on the angle scale, not the slice: find the slice with a running total |
chartXVisibleDomain(length:) on a date axis | Seconds: 7 days is 3600 * 24 * 7 |
[1, 2].reduce(0, +) / 2 as an average | 1: integer division; convert to Double |
Chart(tuples) { ... } with an array of tuples | Compile error: tuples can't be Identifiable; pass id: \.0 |
id: \.0 when the first elements repeat | Two marks share an id: total the data first or use a struct |
if grouped { ... } else { ... } inside Chart | Allowed: the chart builder supports if/else |
.interpolationMethod(.smooth) | Compile error: no such case; use .monotone or .catmullRom |
Viva questions and answers
What is Swift Charts?
Apple's declarative charting framework for SwiftUI, introduced in iOS 16. You describe marks for your data, and it handles the scales, axes, legend and accessibility.
What is a mark?
One visual element drawn for a data value: a bar, line point, dot, area, rule, rectangle or sector. A chart is a collection of marks that share axes.
What does .value("Hours", h) create?
A PlottableValue: a label and a value of a Plottable type such as String, Int, Double or Date. The type decides whether the axis is categorical, numeric or a time scale.
Why must chart data be Identifiable?
Chart(data) loops like ForEach and needs a stable identity for each row, for updates and animation. If the type isn't Identifiable, pass id: with a unique property.
How do you choose a chart type?
By the question: compare categories with bars, show a trend over time with a line, correlation with points, part of a whole with a sector, and a threshold with a rule.
Stacked vs grouped bars?
Bars that share an x value and are split with foregroundStyle(by:) stack by default. Adding position(by:) with the same value puts them side by side.
How do you draw several lines in one chart?
Split the rows into series with foregroundStyle(by:), which also colours them and adds a legend, or with series: in LineMark when they should share a colour.
How do you add an average line?
Compute the average in Swift, then add RuleMark(y: .value("Average", average)) inside the Chart, outside the ForEach, often with a dashed lineStyle and an annotation.
How do you make a donut chart?
Use SectorMark(angle:) with innerRadius: such as .ratio(0.6), and colour slices with foregroundStyle(by:). It needs iOS 17.
foregroundStyle vs foregroundStyle(by:)?
foregroundStyle(.red) paints every mark the same colour. foregroundStyle(by:) maps a data value to colours from a scale and creates a legend; chartForegroundStyleScale picks those colours.
How do you customise an axis?
With chartXAxis or chartYAxis and AxisMarks, choosing values: and the content: AxisGridLine, AxisTick and AxisValueLabel with a format. chartYScale(domain:) fixes the range.
How does chartXSelection work?
It binds to an optional @State of the x axis's type. Charts sets it while the user touches the chart and resets it to nil afterwards; you draw the highlight yourself, usually a RuleMark.
How did you do selection before iOS 17?
With chartOverlay, a GeometryReader and a drag gesture, converting the touch position to a data value with ChartProxy.value(atX:as:).
How do you make a chart scroll?
On iOS 17, add chartScrollableAxes(.horizontal) and chartXVisibleDomain(length:) to say how much is visible; on a date axis the length is in seconds.
Are charts accessible?
Yes. VoiceOver reads each mark using the .value labels and offers Audio Graphs. You can improve the text with accessibilityLabel and accessibilityValue on marks.
Why prepare data before charting?
Charts draw exactly the rows you give them. Grouping, totals, sorting, filling missing days and averages belong in the model, where they can be tested in plain Swift.
Can you chart an array of tuples?
Yes, but tuples can't conform to protocols, so they can't be Identifiable. Pass the id explicitly, Chart(data, id: \.0) or ForEach(data, id: \.0), and make sure that element is unique. For anything lasting, use a struct.
How do you let the user switch between stacked and grouped bars?
Keep a Bool in @State bound to a segmented Picker, and inside the Chart content write if grouped { BarMark(...).position(by:) } else { BarMark(...) }. The chart content builder supports if/else.
How do you approach a chart file that doesn't compile?
Fix the first error first and rebuild, because one error can cause others. Typical causes: missing import Charts, data that isn't Identifiable, a bare value where .value(label, x) is needed, a non-optional selection binding, and wrong enum cases.
Quiz
Which import do you need for
BarMark?Show the answer
import Charts
What is the minimum iOS version for
Chart?Show the answer
iOS 16
Which mark needs iOS 17?
Show the answer
SectorMark
Pie and donut charts arrived in iOS 17. The other marks are iOS 16.
How do you turn vertical bars into horizontal bars?
Show the answer
Swap the x and y values
The category goes on the y axis and the number on the x axis.
Bars use
.foregroundStyle(by: .value("Exam", s.exam))and share x values. How are they drawn?Show the answer
Stacked
Stacking is the default. Add
.position(by:)to group them.Which modifier makes bars grouped side by side?
Show the answer
.position(by:)Which mark best shows whether study hours relate to marks?
Show the answer
PointMark
Two numbers per row and a question about correlation: a scatter plot.
Which mark draws a horizontal target line at 3 hours?
Show the answer
RuleMark(y: .value("Target", 3))A
RuleMarkwith onlyy:spans the width at that y value.What does
innerRadius: .ratio(0.6)do on aSectorMark?Show the answer
Cuts a hole: a donut
Several students' scores are drawn with
LineMarkand noforegroundStyle(by:)orseries:. What appears?Show the answer
A single line through all points
Which interpolation method makes a smooth line that never overshoots the data?
Show the answer
.monotone
Which mark suits a day-by-time-slot heat map?
Show the answer
RectangleMark
What type should
selectedDaybe for.chartXSelection(value: $selectedDay)on a String x axis?Show the answer
String?
It's
nilwhen nothing is selected, so the state must be optional, and its type must match the axis.What does
chartAngleSelectiongive you?Show the answer
A value on the angle scale
You map the value to a slice with a running total of the slice values.
Which modifier sets a custom colour for each category?
Show the answer
.chartForegroundStyleScale([...])On a date axis, what unit is
chartXVisibleDomain(length:)in?Show the answer
Seconds
Before iOS 17, how did you find the data value under a touch?
Show the answer
chartOverlaywithChartProxy.value(atX:as:)What does this print?
Show the answer
["C", "A", "B"]
Highest value first; the tie between A and B is broken by name.
What does this print?
Show the answer
1
Int / Inttruncates. Convert toDoublefor the average line.Why does a weekly line chart map over all day names instead of over the grouped dictionary?
Show the answer
So days with no data appear as 0 and the order is fixed
What does
.value("Day", date, unit: .day)do?Show the answer
Groups each date into a whole-day bin
Why does
Chart(data) { ... }fail whendatais[(String, Int)]?Show the answer
Tuples can't conform to Identifiable
Give the id explicitly:
Chart(data, id: \.0).What does
\.0refer to for an element of type(day: String, count: Int)?Show the answer
The day
How can one Chart switch between stacked and grouped bars at runtime?
Show the answer
if grouped { ... .position(by:) } else { ... }inside the chart contentWhich interpolation method does NOT exist?
Show the answer
.smooth