ModelData.swift


  1. import Foundation
  2. import Combine
  3. final class ModelData: ObservableObject {
  4. @Published var landmarks: [Landmark] = load("landmarkData.json")
  5. var hikes: [Hike] = load("hikeData.json")
  6. var features: [Landmark] {
  7. landmarks.filter { $0.isFeatured }
  8. }
  9. var categories: [String: [Landmark]] {
  10. Dictionary(
  11. grouping: landmarks,
  12. by: { $0.category.rawValue }
  13. )
  14. }
  15. }
  16. func load<T: Decodable>(_ filename: String) -> T {
  17. let data: Data
  18. guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
  19. else {
  20. fatalError("Couldn't find \(filename) in main bundle.")
  21. }
  22. do {
  23. data = try Data(contentsOf: file)
  24. } catch {
  25. fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
  26. }
  27. do {
  28. let decoder = JSONDecoder()
  29. return try decoder.decode(T.self, from: data)
  30. } catch {
  31. fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
  32. }
  33. }