Search code examples
swiftchartsswiftui-charts

Struct doesn't conform to protocol Plottable


I'm attempting to make Swift Chart to work. I have this struct that Xcode says doesn't conform to Plottable. I checked protocol spec and it expect Double, String or Date. Id and Year therefore do not conform. The problem is that even when remove id and year from the struct, Xcode continues to say it doesn't conform to Plottable, and I have no idea why. Hours of searching, trying, and I couldn't make it work.

struct InvestmentData: Identifiable, Plottable {
    var id: Int { year }
    let year: Int
    let principal: Double
    let withReinvestment: Double
    let withoutReinvestment: Double
    let profit: Double
}

Xcode suggests adding protocol stubs, but I have no idea what to do with it.

typealias PrimitivePlottable = <#type#>

I would appreciate any pointers.

Tried:

  1. Removing id and year altogether
  2. Tried writing extension for non-Doubles, but couldn't make it work
  3. Tried changing everything to Double - still says doesn't conform
  4. Tried making new struct with just one var - it doesn't conform either

Solution

  • Do you really need to use Plottable in your implementation? The struct can be used directly in a chart

    Chart(data) {
        BarMark(
            x: .value("Year", $0.year),
            y: .value("Profit", $0.profit)
        )
    }
    

    Although it will look much better with a String as the x value type

    extension InvestmentData {
        var yearLabel: String {
            "\(year)"
        }
    }
    
    Chart(data) {
        BarMark(
            x: .value("Year", $0.yearLabel),
            y: .value("Profit", $0.profit)
        )
    }