Set initial position on scrollable bar chart?

I have a scrollable barmark chart that is introduced in iOS 17 but I have problem to set the initial horizontal scroll position. I want to use the ".chartScrollPosition(initialX:..." but initialX needs to be of type Plottable I can't understand how I can define that. Here is an example, I want it to scroll to the far right (newest days). I show seven days at a time.

import SwiftUI
import Charts

struct ContentView: View {
    let stepDays: [StepDay] = [
        StepDay(date: Calendar.current.date(byAdding: .day, value: -10, to: Date())!, steps: 12342),
        StepDay(date: Calendar.current.date(byAdding: .day, value: -9, to: Date())!, steps: 8345),
        StepDay(date: Calendar.current.date(byAdding: .day, value: -8, to: Date())!, steps: 7656),
        StepDay(date: Calendar.current.date(byAdding: .day, value: -7, to: Date())!, steps: 4564),
        StepDay(date: Calendar.current.date(byAdding: .day, value: -6, to: Date())!, steps: 2344),
        StepDay(date: Calendar.current.date(byAdding: .day, value: -5, to: Date())!, steps: 7654),
        StepDay(date: Calendar.current.date(byAdding: .day, value: -4, to: Date())!, steps: 4532),
        StepDay(date: Calendar.current.date(byAdding: .day, value: -3, to: Date())!, steps: 6788),
        StepDay(date: Calendar.current.date(byAdding: .day, value: -2, to: Date())!, steps: 4567),
        StepDay(date: Calendar.current.date(byAdding: .day, value: -1, to: Date())!, steps: 5678),
        StepDay(date: Date(), steps: 1234)]
    
    var body: some View {
        Chart {
            ForEach(stepDays, id: \.date) { stepDay in
                BarMark(
                    x: .value("Day", stepDay.weekDay),
                    y: .value("Steps", stepDay.steps)
                )
            }
        }
        .chartScrollableAxes(.horizontal)
        .chartXVisibleDomain(length: 7)
//        .chartScrollPosition(initialX: <#T##Plottable#>) // I want to scroll to far right so that I can see the newest days, can I do that with chartScrollPosition(initialX:... ???
    }
}

struct StepDay {
    var date: Date
    var weekDay: String
    var steps: Int
    
    init(date: Date, steps: Int) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "d/M"
        
        self.date = date
        self.weekDay = dateFormatter.string(from: date)
        self.steps = steps
    }
}

Replies

I am almost embarrassed, I solved it, if I ex set .chartScrollPosition(initialX: "19/6"), then it will start at that position.

You can use this to set the initialX value to the 7th-from-the-end element of the stepDays array.

.chartScrollPosition(initialX: stepDays[stepDays.index(stepDays.endIndex, offsetBy: -7, limitedBy: stepDays.startIndex) ?? stepDays.startIndex].weekDay)

This also prevents you getting index out of range errors if the length of the array is less than 7.