forked from NilCoalescing/SwiftUI-Code-Examples
/
Using-Measurements-from-Foundation-as-values-in-Swift-Charts.swift
101 lines (94 loc) · 2.9 KB
/
Using-Measurements-from-Foundation-as-values-in-Swift-Charts.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import SwiftUI
import Charts
struct Walk {
let title: String
let duration: Measurement<UnitDuration>
}
struct ContentView: View {
let walks = [
Walk(
title: "Taylors Mistake to Sumner Beach Coastal Walk",
duration: Measurement(value: 3.1, unit: .hours)
),
Walk(
title: "Bottle Lake Forest",
duration: Measurement(value: 2, unit: .hours)
),
Walk(
title: "Old Halswell Quarry Loop",
duration: Measurement(value: 0.5, unit: .hours)
),
Walk(
title: "Avon River Trail",
duration: Measurement(value: 2.5, unit: .hours)
),
Walk(
title: "Crater Rim Walkway",
duration: Measurement(value: 5, unit: .hours)
),
Walk(
title: "Huntsbury Track",
duration: Measurement(value: 1.5, unit: .hours)
),
Walk(
title: "Omahu Bush and Gibraltar Rock Circuit",
duration: Measurement(value: 2.4, unit: .hours)
),
Walk(
title: "Travis Wetland Walkway",
duration: Measurement(value: 0.7, unit: .hours)
)
]
var body: some View {
VStack(alignment: .leading) {
Text("Comparison of walk durations:")
.font(.headline)
Chart(walks, id: \.title) { walk in
BarMark(
x: .value(
"Duration",
PlottableMeasurement(measurement: walk.duration)
),
y: .value("Walk", walk.title)
)
}
.chartXAxis {
AxisMarks { value in
AxisGridLine()
AxisValueLabel("""
\(value.as(PlottableMeasurement.self)!
.measurement
.converted(to: .hours),
format: .measurement(
width: .narrow,
numberFormatStyle: .number.precision(
.fractionLength(0))
)
)
""")
}
}
.foregroundColor(.orange)
}
.padding(.vertical, 10)
.padding(.horizontal, 8)
.frame(width: 500, height: 400)
.navigationTitle("Chart with measurements")
}
}
struct PlottableMeasurement<UnitType: Unit> {
var measurement: Measurement<UnitType>
}
extension PlottableMeasurement: Plottable where UnitType == UnitDuration {
var primitivePlottable: Double {
self.measurement.converted(to: .minutes).value
}
init?(primitivePlottable: Double) {
self.init(
measurement: Measurement(
value: primitivePlottable,
unit: .minutes
)
)
}
}