ViewLab

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

Contents

  1. What Swift Charts is
  2. Data for a chart
  3. BarMark
  4. LineMark, PointMark and AreaMark
  5. RuleMark, RectangleMark and SectorMark
  6. Which mark for which question
  7. Customising a chart
  8. Selection and scrolling
  9. Preparing chart data in plain Swift
  10. 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.

The smallest useful chart: one BarMark per element
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)
    }
}

Availability

APIMinimum iOS
Chart, BarMark, LineMark, PointMark, AreaMark, RuleMark, RectangleMarkiOS 16
Axes, scales, legends, annotation, chartOverlay + ChartProxyiOS 16
SectorMark (pie and donut)iOS 17
chartXSelection, chartYSelection, chartAngleSelectioniOS 17
chartScrollableAxes, chartXVisibleDomain, chartScrollPositioniOS 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.

Try “What Swift Charts is” with live code →

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.

Four ways to feed data to a Chart
// 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.5

Plottable types

Swift typeAxis kindExample
StringCategorical: one slot per distinct value.value("Subject", "Maths")
Int, Double, FloatQuantitative: a continuous number line.value("Hours", 2.5)
DateTemporal: 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.

This doesn't compile
struct SubjectHours {
    let subject: String
    let hours: Double
}
let rows = [SubjectHours(subject: "Maths", hours: 2)]
let first: SubjectHours = rows.first

first 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.

\.day and \.0 name the same element: labels are just names for positions.
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))
        }
    }
}
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 6100

Try “Data for a chart” with live code →

BarMark

BarMark compares values across categories. Which axis gets the category decides the direction.

Swap x and y to turn the bars sideways
// 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

foregroundStyle(by:) colours by series; position(by:) groups
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

yStart/yEnd and xStart/xEnd draw ranges
// 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 wantWrite
Vertical barsBarMark(x: category, y: number)
Horizontal barsBarMark(x: number, y: category)
Stacked by series.foregroundStyle(by: .value("Series", s))
Grouped side by sideadd .position(by: .value("Series", s))
100% stackedBarMark(..., stacking: .normalized)
Floating rangeBarMark(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:

Both branches must be chart content (marks), not views like Text.
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.0

Try “BarMark” with live code →

LineMark, PointMark and AreaMark

LineMark: trends

LineMark joins points in x order. Use it for a trend over time (days, weeks, months).

Two ways to split data into several lines
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)
    )
}
interpolationMethodShape
.linear (default)Straight segments between points
.catmullRomSmooth curve through every point (can overshoot)
.monotoneSmooth curve that never overshoots between points
.stepStart, .stepCenter, .stepEndSteps: the value jumps, like a price or level change
.cardinalSmooth 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?

symbol(by:) gives each series its own shape: helpful for colour-blind readers
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

AreaMark stacks by series, like BarMark
// 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:

What does this print?
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]

Try “LineMark, PointMark and AreaMark” with live code →

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).

Bars plus an average line: compute average first
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.86

RectangleMark: heat maps

Two categories on the axes, a number as the colour
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)

A donut chart. Remove innerRadius for a pie
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)

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 questionMarkExample
Compare values across categoriesBarMarkHours per subject
Trend over timeLineMarkHours per day this week
Correlation between two numbersPointMarkStudy hours vs marks
Part of a wholeSectorMarkShare of time per subject
A threshold, target or averageRuleMarkDaily target of 3 hours
Volume or cumulative amount over timeAreaMarkHours per subject, stacked per week
A value for each cell of a matrixRectangleMarkMinutes per day and time slot
A range (min to max)BarMark with yStart/yEndLowest 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.

Marks drawn later sit on top
// 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))
}

Try “Which mark for which question” with live code →

Customising a chart

Colours

foregroundStyle vs foregroundStyle(by:) vs chartForegroundStyleScale
// 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,
])
ModifierApplies toEffect
.foregroundStyle(.red)A markSame colour for every mark, no legend
.foregroundStyle(by: .value(...))A markColour per value, automatic legend
.chartForegroundStyleScale([...])The ChartWhich colour each value gets

Axes and scale

Custom axes, a fixed y range and axis titles
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)

Legend, annotations and accessibility

Labels on bars, legend position and VoiceOver text
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.5

Try “Customising a chart” with live code →

Selection 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.

The x axis holds String, so the selection is String?
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
Dim the slices that aren't selected
@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 above

Scrolling (iOS 17)

A scrolling chart showing one week at a time
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

iOS 16: convert the touch position into a data value yourself
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 }
            )
    }
}

Try “Selection and scrolling” with live 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
StepCodeResult type
Group rows by a keyDictionary(grouping: rows, by: { $0.subject })[String: [StudySession]]
Total each group.mapValues { $0.reduce(0.0) { $0 + $1.hours } }[String: Double]
Same total in one looptotals[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

What does this print?
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]
7
This doesn't compile
var totals: [String: Double] = [:]
totals["Maths"] += 2.5

totals["Maths"] is Double?, and += doesn't work on an optional. Write totals["Maths", default: 0] += 2.5.

What does this print?
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.0
What does this print?
let hours = [1, 2]
print(hours.reduce(0, +) / hours.count)
print(Double(hours.reduce(0, +)) / Double(hours.count))
Show the answer
1
1.5

Try “Preparing chart data in plain Swift” with live code →

Bug 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.

Five defects that are only visible on screen.
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 Int before dividing, so the average is truncated and the rule sits too low. (It also divides by zero when sales is 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:) or series:, 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 RuleMark is inside the ForEach, so one identical rule is drawn per row. Fix: Move it out of the ForEach, after it, inside Chart { }.
  • [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 with foregroundStyle(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 .annotation that lists the amounts for that month.

Try “Bug hunt: charts that compile but mislead” with live code →

Exam traps

Code or claimWhat really happens
Minimum iOS for Chart and BarMarkiOS 16
Minimum iOS for SectorMark and chartXSelectioniOS 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 IdentifiableCompile error: make it Identifiable or pass id:
Category order on the axisOrder of first appearance in the data, not alphabetical: sort the array
BarMark(x: number, y: category)Horizontal bars
Bars with foregroundStyle(by:) onlyStacked, not grouped
Grouped barsAdd .position(by: .value(...))
LineMark for several students without foregroundStyle(by:) or series:One zigzag line through every point
.interpolationMethod(.catmullRom) vs .monotoneBoth 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:) valuesRaw values; Charts works out each share of the total
Donut vs pieDonut 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 StringCompile error: the binding must be optional (String?)
chartAngleSelection resultA number on the angle scale, not the slice: find the slice with a running total
chartXVisibleDomain(length:) on a date axisSeconds: 7 days is 3600 * 24 * 7
[1, 2].reduce(0, +) / 2 as an average1: integer division; convert to Double
Chart(tuples) { ... } with an array of tuplesCompile error: tuples can't be Identifiable; pass id: \.0
id: \.0 when the first elements repeatTwo marks share an id: total the data first or use a struct
if grouped { ... } else { ... } inside ChartAllowed: 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

  1. Which import do you need for BarMark?

    Show the answer

    import Charts

  2. What is the minimum iOS version for Chart?

    Show the answer

    iOS 16

  3. Which mark needs iOS 17?

    Show the answer

    SectorMark

    Pie and donut charts arrived in iOS 17. The other marks are iOS 16.

  4. 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.

  5. 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.

  6. Which modifier makes bars grouped side by side?

    Show the answer

    .position(by:)

  7. 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.

  8. Which mark draws a horizontal target line at 3 hours?

    Show the answer

    RuleMark(y: .value("Target", 3))

    A RuleMark with only y: spans the width at that y value.

  9. What does innerRadius: .ratio(0.6) do on a SectorMark?

    Show the answer

    Cuts a hole: a donut

  10. Several students' scores are drawn with LineMark and no foregroundStyle(by:) or series:. What appears?

    Show the answer

    A single line through all points

  11. Which interpolation method makes a smooth line that never overshoots the data?

    Show the answer

    .monotone

  12. Which mark suits a day-by-time-slot heat map?

    Show the answer

    RectangleMark

  13. What type should selectedDay be for .chartXSelection(value: $selectedDay) on a String x axis?

    Show the answer

    String?

    It's nil when nothing is selected, so the state must be optional, and its type must match the axis.

  14. What does chartAngleSelection give 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.

  15. Which modifier sets a custom colour for each category?

    Show the answer

    .chartForegroundStyleScale([...])

  16. On a date axis, what unit is chartXVisibleDomain(length:) in?

    Show the answer

    Seconds

  17. Before iOS 17, how did you find the data value under a touch?

    Show the answer

    chartOverlay with ChartProxy.value(atX:as:)

  18. What does this print?

    Show the answer

    ["C", "A", "B"]

    Highest value first; the tie between A and B is broken by name.

  19. What does this print?

    Show the answer

    1

    Int / Int truncates. Convert to Double for the average line.

  20. 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

  21. What does .value("Day", date, unit: .day) do?

    Show the answer

    Groups each date into a whole-day bin

  22. Why does Chart(data) { ... } fail when data is [(String, Int)]?

    Show the answer

    Tuples can't conform to Identifiable

    Give the id explicitly: Chart(data, id: \.0).

  23. What does \.0 refer to for an element of type (day: String, count: Int)?

    Show the answer

    The day

  24. How can one Chart switch between stacked and grouped bars at runtime?

    Show the answer

    if grouped { ... .position(by:) } else { ... } inside the chart content

  25. Which interpolation method does NOT exist?

    Show the answer

    .smooth

← Lifecycle, animation and persistence

Practise this lesson interactively →