Creating Bar Chart in SwiftUI

DevTechie
DevTechie
Published in
3 min readJan 26, 2022

--

Photo by Giorgio Tomassetti on Unsplash

Today, we will be building bar char in SwiftUI. For our bar chart data, we will create sample data from fictitious monthly expense app.

Our final output will look like this:

We will start with an enum to represent our months.

enum Month: String, CaseIterable {
case jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec
}

Next, we will create our MonthlyExpense model which will have month as well as expense for that month.

struct MonthlyExpense: Identifiable {
var id = UUID()
var month: Month
var value: Double
var name: String {
month.rawValue.capitalized
}
}

Let’s add some sample data to our MonthlyExpense struct. We will also add a static computed property to find out max value from our sample data, which we will use to compute bar’s height by normalizing the value with a simple math formula.

extension MonthlyExpense {
static var sampleData: [MonthlyExpense] {
[
MonthlyExpense(month: Month.jan, value: 5000),
MonthlyExpense(month: Month.feb, value: 2000),
MonthlyExpense(month: Month.mar…

--

--