How it works
A PhysicalMetricsConverter translates between the abstract point values that SwiftUI lays out in and the real-world physical lengths those points occupy in 3D space. On platforms where a view's content has a true physical extent, a point is not a fixed size, so any time you need a layout dimension expressed in actual units — meters, centimeters, inches — you reach for a converter rather than hard-coding a number. Use it to keep on-screen measurements honest: derive a size in points from a physical quantity, or report a physical quantity back from a point-based dimension, always relative to the environment the converter is bound to.
Obtain a converter for the current context
A
PhysicalMetricsConverteris meaningful only against a particular display environment, which determines how points map to physical length. In the example a single instance is held asprivate let converter = PhysicalMetricsConverter()so the rest of the view can ask it for conversions; in production you typically resolve one tied to the active scene rather than constructing it free-standing.Convert a physical quantity into a value for the view
The converter's job is the round trip between physical units and the numbers SwiftUI uses. Each call hands the converter a real-world measurement and gets back a context-appropriate result — here
converter.localizedString(fromMeters: 1.78)turns a height in meters into a presentable value, so the displayed figure tracks the environment instead of being a frozen constant.Drive multiple metrics from one converter
Because the converter is just a value you call methods on, a single instance services every dimension a view cares about. The example reuses the same
converterforlocalizedString(fromKilograms: 72.5)alongside the height conversion, so weight and height are resolved consistently against the same physical context.Surface the converted values in the layout
The converter produces plain values that you feed straight into ordinary views — it does not render anything itself. The two
LabeledContentrows for"Height"and"Weight"simply display whatever the converter returns; the symbol's contribution is the converted number, and the surroundingVStackis only the place it lands.
fromMeters: 1.78 to a different height and watch the "Height" row update, confirming the displayed value is computed by the converter rather than typed in.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct PhysicalMetricsConverterDemo: View {
private let converter = PhysicalMetricsConverter()
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Physical Metrics")
.font(.headline)
LabeledContent("Height",
value: converter.localizedString(fromMeters: 1.78))
LabeledContent("Weight",
value: converter.localizedString(fromKilograms: 72.5))
}
.padding()
}
}