Member-only story

Introduction to Charts in SwiftUI

Bruno Lorenzo
7 min readJan 23, 2024

--

Image by Author

When it comes to presenting information to users, easier is better.

Especially when we're dealing with large sets of data. We have different options like custom views, tables, summaries, etc. However, we can take a much richer experience path, and use some graphical presentation.

By using charts, users can get, at first sight, a better understanding of the data presented.

If you're looking to elevate your app's engagement, let me show you a quick, easy-to-follow guide on how we leverage charts to do it.

Source code available here

The basics

We create a chart by composing a series of chart elements. These elements must conform ChartContent protocol and represent types that can be drawn in a chart's scope.

To create a chart, we use the init(content:) method. In the ViewBuilder closure, we add all the visual elements needed.

struct ChartView: View {
var body: some View {
ChartView {
// Chart elements
}
}
}

Ok, but what elements can we add?

Charts framework has a pre-defined set of ChartContent ready to use called Marks. You can see a Mark as a graphical element that represents data.

Image by Author

Each Mark type has several initializers to use depending on what UI we want to achieve.

We can use 3 types of data in charts

  1. Quantitative: Numerical values like Int, Double, and Float.
  2. Nominal: Discrete categories or groups.
  3. Temporal: Point in time.

Depending on the data type that we use, the configurations that we can apply to manipulate the charts' UI.

Show me the code 🤓

For our demo, we want to present the number of coffees that users consume over time, grouped by type (latte, cappuccino…

--

--

Bruno Lorenzo
Bruno Lorenzo

Written by Bruno Lorenzo

Software Engineer | Co-creator of https://carry-on.app - A travel planner app | Former iOS Tech Lead | I write about iOS, tech, and producitivy

Responses (3)

Write a response