Chart Data driven

And we can make the bar chart data driven with ForEach.

💙 Swift Chart automatically chooses an appropriate axis style to make the chart beautiful.

// We create data
// We use ForEach to iterate over the data

import Charts
import SwiftUI

struct Wines: Identifiable {
    var name: String
    var sales: Int
    
    var id: String { name }
}

let sales: [Wines] = [
    .init(name: "Margaux", sales: 500),
    .init(name: "Médoc", sales: 460),
    .init(name: "Blaye", sales: 300),
    .init(name: "St Estèphe", sales: 290),
    .init(name: "Sauternes", sales: 250),
    .init(name: "Pessac-Léognan", sales: 20)
]

struct ContentView: View {
    @State private var selection = 2
    
    var body: some View {
        TabView(selection: $selection) {
            WinesTab()
                .tabItem {
                    Label("Wines", systemImage: "chart.bar.doc.horizontal")
                }
                .tag(1)
        }
    }
}

struct WinesTab: View {
    var body: some View {
        Chart {
            ForEach(sales) { element in
                BarMark (
                    x: .value("Name", element.name),
                    y: .value("Sales", element.sales)
                )
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Last updated