Reading time: 1 min

This quick recipe shows how to convert AxisValue to a Text using Apple's new Charts Framework.

The end result looks like this:


Charts framework is available starting in SwiftUI 4 (iOS 16, macOS 12.4).

When you construct X or Y axis in SwiftUI charts using chartXAxis or chartYAxis, you usually pass the AxisMarks result builder. It provides its block with an AxisValue instance the represents the current axis mark. However, it only knows its index and total count - but not its actual value.

The key is to cast the value to a primitive with as(:) method. The example below plots integers on the Y axis, so cast to Int.self is correct:

Chart {
  // ...
.chartYAxis {
  AxisMarks(values: .automatic) { value in
    AxisGridLine(centered: true, stroke: StrokeStyle(dash: [1, 2]))
    AxisTick(centered: true, stroke: StrokeStyle(lineWidth: 2))
    AxisValueLabel() {
      if let intValue = { // HERE
        Text("\(intValue) km")
          .font(.system(size: 10))

Next Post Previous Post