An Introduction into Swift Charts

A barebones no frills introduction to displaying the most basic of charts, a Bar Chart.

Rob Maltese
oneleif
3 min readDec 3, 2022

--

Swift Charts is a powerful and user-friendly library for creating beautiful and engaging charts in iOS applications. With a simple, and easy implementation method and a wide range of customization options, Swift Charts allows developers to quickly and easily create a variety of chart types, including line, and bar charts. Whether you’re a beginner or an experienced developer, Swift Charts is an essential tool for creating engaging data visualizations in your iOS app.

Mobile telephone on a desk displaying a line chart trending downward.
Swift Charts allow you to add simple and easy views to display your data.

Great, so how do I implement Swift Charts?

Within the view in which you’d like to display your Chart, simply import the charts librarly.

import Charts

Then within your view body, you’ll simply implement a simple chart of your choice, such as BarMark. We’ll implement it in this method within a ForEach in order to allow for customization in the future.

import SwiftUI
import Charts

struct ChartView: View {
var body: some View {
VStack {
Chart {
ForEach(yourDataSet) { data in
BarMark(
x: .value("Data Date", data.date, value: .week)
y: .value("Data Price", data.price)
)
}
}
}
}
}

Your data set will need to conform to Random Access Collection and be Identifiable. For instance, you could create a model for an object you want to represent data for, and then create an array of that model. If your model does not conform to Identifiable, you could get away with simply adding id: \.self within the ForEach parameters.

As you can see within the XAxis, there is an added parameter called value. If your data model has a variable you’re using within your chart that is of type Date, Swift will automatically infer that you’re looking to select a DateComponent to set as the value. Which means, you will be able to narrow your data set down to any DateComponent.

BarChart displaying a weekly average price chart for oil prices.
The chart framework easily allows for the adoption of dark mode with no additional implementation.

As simple as that, we have drawn out a very basic implementation of a Bar Chart. From here, we can work on customizing them to our liking using simple view modifiers provided by the library. In the next article on Swift Charts, I’ll detail how I obtained the above visual design.

In conclusion, Apple did a great job with this framework as it is incredibly intuitive. It provies developers with a very easy way to implement beautiful adaptive graphics to represent various types of data. Unfortunately, the one big chart missing is a Pie Chart… However, after speaking with the Apple Evangelists during one of the WWDC22 Slack Sessions they do have plans to implement them in the future.

--

--