How to Create Line Charts with SwiftUI Charts in iOS 16
The Charts framework is one of my favourite features for the new version of SwiftUI in iOS 16. Prior to iOS 16, you need to build your own charts or rely on third party library to render charts for you. With the release of this new framework, Apple has made it very easy for developers to create animated and interactive charts.
I have briefly discussed the usage of the Charts API in this post. For this tutorial, let’s see how to use the APIs to create a line chart.
The Weather Data
To demonstrate the SwiftUI Charts API, we will create a line chart that displays the average temperature of Hong Kong, Taipei, and London from 2021-Jul to 2022-Jun.
To store the weather data, I created a WeatherData
struct like below:
struct WeatherData: Identifiable {
let id = UUID()
let date: Date
let temperature: Double
init(year: Int, month: Int, day: Int, temperature: Double) {
self.date = Calendar.current.date(from: .init(year: year,month: month, day: day)) ?? Date()
self.temperature = temperature
}
}
The Chart
initializer takes in a list of Identifiable
objects. This is why we make the WeatherData
conform the Identifiable
protocol.
For each city, we create an array to store the weather data. Here is an example for London:
let londonWeatherData = [ WeatherData(year: 2021, month: 7, day: 1,temperature: 19.0)…