Hello Swift Charts: Swift Charts with SwiftUI

 

David Ametsitsi

David is an experienced mobile engineer, always looking to push the envelope of AR/VR experiences.

Updated Aug 19, 2022

With growing adoption of SwiftUI, Apple is continuously adding new features and frameworks to help developers build delightful experiences for their users and do it quickly. This year’s WWDC22 was no exception, one major update that caught my attention was Swift Charts. 

If you work with data represented in charts, Swift Charts is a much needed simplification for creating charts in SwiftUI. Because Swift Charts is built off of Swift UI, it uses the same familiar declarative syntax as SwiftUI so it is easy for current developers to hit the ground running.

Line charts

Line charts are a great way to visualize trending data. In this example, we have temperature graphed over time:

 

Let’s implement this graph first in SwiftUI, then using Swift Charts:

Using SwiftUI:

var body: some View {
  chartView
    .frame(height: 200)
    .background(chartBackground)
    .overlay(chartYAxis, alignment: .leading)
}

private var chartView: some View {
  GeometryReader { geometry in
    Path { path in
      for index in data.indices {
        let xPosition = geometry.size.width / CGFloat(data.count) * CGFloat(index + 1)
        let yAxis = maxY - minY
        let yPosition = CGFloat(1 - (data[index] - minY) / yAxis) * geometry.size.height
        if index == 0 {
          path.move(to: CGPoint(x: xPosition, y: yPosition))
        }
        path.addLine(to: CGPoint(x: xPosition, y: yPosition))
      }
    }
    .stroke(Color.blue, style: StrokeStyle(lineWidth: 2, lineCap: .round, lineJoin: .round))
  }
}

private var chartBackground: some View {
  VStack {
    Divider()
    Spacer()
    Divider()
    Spacer()
    Divider()
    Spacer()
    Divider()
    Spacer()
    Divider()
  }
}

private var chartYAxis: some View {
  VStack {
    Text(String(maxY))
    Spacer()
    Text(String((minY + (maxY - minY) * 0.75)))
    Spacer()
    Text(String((minY + (maxY - minY) * 0.50)))
    Spacer()
    Text(String((minY + (maxY - minY) * 0.25)))
    Spacer()
    Text(String(minY))
  }
}

Using Swift Charts:

var body: some View {
  Chart {
    ForEach(data) { temp in
      LineMark(
        x: .value("Time", temp.time),
        y: .value("Temp", temp.value)
      )
    }
  }
  .frame(height: 200)
}

Scatter plots

Scatter plots are a useful way to plot data in relation to each other. In this example, we have temperature vs humidity:

 

 

Let’s implement this graph first in SwiftUI, then using Swift Charts:

 

Using SwiftUI:

var body: some View {
  chartView
    .frame(height: 200)
    .background(chartBackground)
    .overlay(chartYAxis, alignment: .leading)
}

private var chartView: some View {
  GeometryReader { geometry in
    let xAxis = maxX - minX
    let yAxis = maxY - minY
    ForEach(data) { day in
      let xPosition = CGFloat(day.humidity) * (geometry.size.width / xAxis)
      let yPosition = CGFloat(1 - (day.value - minY) / yAxis) * geometry.size.height
      Circle()
        .frame(width: 5)
        .position(x: xPosition, y: yPosition)
    }
  }
}

private var chartBackground: some View {
  VStack {
    Divider()
    Spacer()
    Divider()
    Spacer()
    Divider()
    Spacer()
    Divider()
    Spacer()
    Divider()
  }
}

private var chartYAxis: some View {
  VStack {
    Text(String(maxY))
    Spacer()
    Text(String((minY + (maxY - minY) * 0.75)))
    Spacer()
    Text(String((minY + (maxY - minY) * 0.50)))
    Spacer()
    Text(String((minY + (maxY - minY) * 0.25)))
    Spacer()
    Text(String(minY))
  }
}

Using Swift Charts:

var body: some View {
  Chart {
    ForEach(data) { temp in
      PointMark(
        x: .value("Humidity", temp.humidity),
        y: .value("Temp", temp.value)
      )
      .symbolSize(20)
    }
  }
}

Bar graphs

Bar graphs are a descriptive way to visualize measurement data. In this example, we are using a bar graph to visualize rainfall for 8 days.

 

Let’s implement this graph first in SwiftUI, then using Swift Charts:

Using SwiftUI: 

var body: some View {
  GeometryReader { geometry in
    VStack {
      HStack {
        chartYAxis
        chartView
          .background(chartBackground)
      }
      chartXAxisLabels
    }
    .frame(width: geometry.size.width, height: geometry.size.height)
  }
}

Using Swift Charts:


  var body: some View {
    Chart(data) { rainData in
      BarMark(
        x: .value("Time", rainData.time),
        y: .value("Rain", rainData.value)
      )
    }
  }
  

What are the pros and cons of Swift Charts and SwiftUI?

Swift Charts

Pros:

  • Easier to get started
  • Less code
Cons:
  • Only available in Beta(Requires iOS 16+)
  • Less flexible(for now)

SwiftUI

Pros:

  • More flexible
  • More code
Cons:
  • Requires more complex layout
  • Requires more calculations

3rd Party Libraries

Pros:

  • Often very flexible
  • Have a lot of support in 3rd party community

Cons:

  • Requires more complex layout
  • Requires more calculations
  • 3rd party libs often become a pain to support
  • 3rd party libs often become obsolete
  • Less likely to be long term solutions

Swift Charts allows developers to create graphs much faster and easier than before. It requires less code and uses the same familiar syntax as SwiftUI. It is currently only available in beta(iOS 16+), but it will soon be production ready. One downside is that Swift Charts is currently not very flexible, using SwiftUI or another alternative charting library may be better suited for more complex graphs and visualizations.

Looking for more information? 

Videos:

Create a custom line chart to display historical price data: This is a video detailing how to create charts for a crypto trading app using SwiftUI

Swift Charts: Raise the bar: This is a video detailing how to create charts using Swift Charts 

Articles:

Creating a chart using Swift Charts: This is Apple article on Swift Charts

Swift UI Tutorial for iOS: Creating Charts: This is an article detailing how to create charts using Swift UI

Documentation:

Swift Charts: This is Apple’s main documentation for Swift Charts

How can we help?

Can we help you apply these ideas on your project? Send us a message...