UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Strange runtime error when trying to display a barmark with different coloured bars

Forums > SwiftUI

I have this very strange error. I'm trying to display a simple BarMark chart, code below. It compiles fine but when I run the app and display the chart I get the error:

Charts/ConcreteScale+Discrete.swift:128: Fatal error: Unexpectedly found nil while unwrapping an Optional value 2023-01-12 17:05:15.169986+0100 appname[54727:938178] Charts/ConcreteScale+Discrete.swift:128: Fatal error: Unexpectedly found nil while unwrapping an Optional value

The error is caused by the line: .foregroundStyle(by: .value("Bar Color", items.color))

I want the first 3 bars to be displayed in Red and the second 3 bars in green.

What am I doing wrong?

 struct Item: Identifiable {
        let id = UUID()
        let month: String
        let visitValue: Int
        let color: String
    }

    var myItems = [Item]()
    let items:  [Item] = [

                // Highest performing Months
                Item(month: highestLowestMonths.mthHighestName[0],
                visitValue: Int(highestLowestMonths.mthHighestRevenue[0]),
                color: "red"),

                Item(month: highestLowestMonths.mthHighestName[1],
                visitValue: Int(highestLowestMonths.mthHighestRevenue[1]),
                color: "red"),

                Item(month: highestLowestMonths.mthHighestName[2],
                visitValue: Int(highestLowestMonths.mthHighestRevenue[2]),
                color: "red"),

                // Lowest performing Months
                Item(month: highestLowestMonths.mthLowestName[0],
                visitValue: Int(highestLowestMonths.mthLowestRevenue[0]),
                color: "green"),

                Item(month: highestLowestMonths.mthLowestName[1],
                visitValue: Int(highestLowestMonths.mthLowestRevenue[1]),
                color: "green"),

                Item(month: highestLowestMonths.mthLowestName[2],
                visitValue: Int(highestLowestMonths.mthLowestRevenue[2]),
                color: "green")
    ]

    var body: some View {

                Chart {
                    // High and low monthly performers chart
                    ForEach(items) { items in
                        BarMark(
                            x: .value("Month", items.month),
                            y: .value("contact Revenue", items.visitValue)
                        )
                        //.foregroundStyle(.green.opacity(0.8))
        >>>>>>            .foregroundStyle(by: .value("Bar Color", items.color))    <<<<<<<<
                    }
                }

                .chartForegroundStyleScale([
                    "zzz": Color(.green)
                     ])
                .chartLegend(position: .top, alignment: .bottomTrailing)
                .chartYAxis(.hidden)

                // Chart has been tapped. display large version.
                .onTapGesture {
                    print("mob: High and low monthly performers chart tapped")
                    showLargeChart = true
                    }
                    .sheet(isPresented: $showLargeChart) {
                    summaryChartLarge()
                    }
            }
        }

1      

@flaneur swatting bugs:

I have this very strange error....

Think of item as ONE thing in your collection of items.
Think of cat as ONE cat in your collection of pets.
Think of auto as ONE car in your collection of cars.

ForEach (cars) { auto in   // <-- cars is the collection. auto is ONE of those things
    Text( auto.model )   
}

ForEach (pets) { cat in // <-- pets is the collection. ca is ONE of those pets.
    Text( cat.name )
}

In your code you have a confusion between your collection (items) and the things in your collection (also call items?) Try to use real world names of things. What are you attempting to graph? Use those real world names to help you with your logic.

It seems you have salesmen and sales data?

ForEach(items) { items in  // <-- This is confusing.
          BarMark(
             x: .value("Month", items.month),
             y: .value("contact Revenue", items.visitValue)
           )
       //.foregroundStyle(.green.opacity(0.8))  >>>>>>            .foregroundStyle(by: .value("Bar Color", items.color))    <<<<<<<<
}

1      

My guess is you need both colors here:

.chartForegroundStyleScale([
                    "zzz": Color(.green)
                     ])

1      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.