Created
September 2, 2022 12:02
-
-
Save Drag0ndust/c6feadf20307e45b903c4e31f3386706 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import Charts | |
struct Temperature: Identifiable { | |
var id: String { day } | |
let day: String | |
let degree: Double | |
} | |
struct City: Identifiable { | |
var id: String { name } | |
let name: String | |
let temperatures: [Temperature] | |
var average: Double { | |
let result = temperatures.reduce(0) { partialResult, temperature in | |
return partialResult + temperature.degree | |
} | |
return result / Double(temperatures.count) | |
} | |
} | |
class ViewModel: ObservableObject { | |
@Published var cities: [City] = [ | |
City(name: "Karlsruhe", temperatures: [ | |
.init(day: "Monday", degree: 31), | |
.init(day: "Tuesday", degree: 35), | |
.init(day: "Wednesday", degree: 39), | |
.init(day: "Thursday", degree: 23), | |
.init(day: "Friday", degree: 25), | |
.init(day: "Saturday", degree: 19.5), | |
.init(day: "Sunday", degree: 32.8) | |
]), | |
City(name: "Frankfurt", temperatures: [ | |
.init(day: "Monday", degree: 28), | |
.init(day: "Tuesday", degree: 23), | |
.init(day: "Wednesday", degree: 34), | |
.init(day: "Thursday", degree: 18), | |
.init(day: "Friday", degree: 19.6), | |
.init(day: "Saturday", degree: 21.5), | |
.init(day: "Sunday", degree: 26.8) | |
]) | |
] | |
} | |
struct ChartView: View { | |
@ObservedObject private var model: ViewModel = ViewModel() | |
var body: some View { | |
Chart(model.cities) { city in | |
RuleMark(y: .value("Average", city.average)) | |
.foregroundStyle(by: .value("City", city.name)) | |
ForEach(city.temperatures) { temperature in | |
LineMark(x: .value("Day", temperature.day), | |
y: .value("Temperature", temperature.degree)) | |
} | |
.position(by: .value("City", city.name)) | |
.symbol(by: .value("City", city.name)) | |
.foregroundStyle(by: .value("City", city.name)) | |
} | |
.chartYScale(domain: 15 ... 40) | |
.frame(height: 300) | |
.padding() | |
} | |
} | |
struct ChartView_Previews: PreviewProvider { | |
static var previews: some View { | |
ChartView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment