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()
}
}
}