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. @Published var profile = Profile.default
  7. var features: [Landmark] {
  8. landmarks.filter { $0.isFeatured }
  9. }
  10. var categories: [String: [Landmark]] {
  11. Dictionary(
  12. grouping: landmarks,
  13. by: { $0.category.rawValue }
  14. )
  15. }
  16. }
  17. func load<T: Decodable>(_ filename: String) -> T {
  18. let data: Data
  19. guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
  20. else {
  21. fatalError("Couldn't find \(filename) in main bundle.")
  22. }
  23. do {
  24. data = try Data(contentsOf: file)
  25. } catch {
  26. fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
  27. }
  28. do {
  29. let decoder = JSONDecoder()
  30. return try decoder.decode(T.self, from: data)
  31. } catch {
  32. fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
  33. }
  34. }