History
Loading...
Loading...
September 26, 2025
MeasurementFormatter with Swift Charts to automatically handle unit conversions and localization. Instead of manually formatting chart values, let the system handle currency, percentages, and measurements with proper locale support using .chartYAxis { AxisMarks(format: .currency(code: "USD")) }This practice uses built-in formatters for chart axes instead of manually converting values to strings. The currency formatter automatically handles locale-specific formatting, while the date formatter provides consistent date display.
import SwiftUI
import Charts
struct SalesChart: View {
let salesData: [(month: String, revenue: Double)]
var body: some View {
Chart(salesData, id: \.month) { data in
BarMark(
x: .value("Month", data.month),
y: .value("Revenue", data.revenue)
)
.foregroundStyle(.blue.gradient)
}
.chartYAxis {
AxisMarks(format: .currency(code: "USD").precision(.fractionLength(0)))
}
.chartXAxis {
AxisMarks { _ in
AxisGridLine()
AxisValueLabel(format: .dateTime.month(.abbreviated))
}
}
.frame(height: 300)
}
}Built-in formatters ensure proper localization, reduce code complexity, and provide consistent formatting across different regions. They also handle edge cases like negative values, large numbers, and accessibility requirements automatically.