I have a Swift program whose ContentView is a navigation view. The left side of the navigation view allows me to select/display one of three views which are graphs of data from 3 different JSON files. Each of these three views utilizes a ViewModel and a DataModel. The ViewModels are a class and the DataModels are a structure that calls a class that reads the JSON file. Two of the JSON files have identical formats so I would like to eliminate one DataModel which will require that I pass to the DataModel class the file name (just the filename, the extension is always .json). If someone could point me in the right direction it would be appreciated. Below is one of the ViewModels and its associated DataModel.
import Foundation
class VFIAXDataViewModel: ObservableObject {
@Published private var vfiaxDataModel: VFIAXDataModel = VFIAXDataModel()
var timeSeriesDaily : [(Date, Double)] {
return vfiaxDataModel.vfiaxData.timeSeriesData.timeSeriesDaily
}
}
class VFIAXData {
var timeSeriesData = VFIAXTimeSeriesData(timeSeriesDaily: [])
init() {
getData()
}
func getData() {
guard let url = Bundle.main.url(forResource: "VFIAXData10", withExtension: "json")
else {
print("Json file not found")
return
}
let decoder = JSONDecoder()
do {
let data = try Data(contentsOf: url)
self.timeSeriesData = try decoder.decode(VFIAXTimeSeriesData.self, from: data)
self.timeSeriesData.timeSeriesDaily = self.timeSeriesData.timeSeriesDaily.sorted() { $0 < $1 }
let lastYear: Date = Calendar.current.date(byAdding: .year , value: -1, to: timeSeriesData.timeSeriesDaily[timeSeriesData.timeSeriesDaily.count - 1].0) ?? Date()
var index = 0
for i in 0...(timeSeriesData.timeSeriesDaily.count - 1) {
if timeSeriesData.timeSeriesDaily[i].0 >= lastYear {
index = i
break
} // end if
} // for loop
timeSeriesData.timeSeriesDaily.removeSubrange(0..<index)
} catch {
print(error)
}
}
}
struct VFIAXDataModel {
var vfiaxData = VFIAXData()
}