TempTargetPreset.swift 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. //
  2. // TempTargetPreset.swift
  3. // LoopFollow
  4. //
  5. // Created by Jonas Björkert on 2024-07-31.
  6. // Copyright © 2024 Jon Fawcett. All rights reserved.
  7. //
  8. import Foundation
  9. import HealthKit
  10. struct TempTargetPreset: Identifiable, Codable {
  11. var id: UUID
  12. var name: String
  13. var target: HKQuantity
  14. var duration: HKQuantity
  15. enum CodingKeys: String, CodingKey {
  16. case id, name, targetValue, durationValue
  17. }
  18. init(id: UUID = UUID(), name: String, target: HKQuantity, duration: HKQuantity) {
  19. self.id = id
  20. self.name = name
  21. self.target = target
  22. self.duration = duration
  23. }
  24. init(from decoder: Decoder) throws {
  25. let container = try decoder.container(keyedBy: CodingKeys.self)
  26. id = try container.decode(UUID.self, forKey: .id)
  27. name = try container.decode(String.self, forKey: .name)
  28. let targetValue = try container.decode(Double.self, forKey: .targetValue)
  29. target = HKQuantity(unit: .milligramsPerDeciliter, doubleValue: targetValue)
  30. let durationValue = try container.decode(Double.self, forKey: .durationValue)
  31. duration = HKQuantity(unit: .minute(), doubleValue: durationValue)
  32. }
  33. func encode(to encoder: Encoder) throws {
  34. var container = encoder.container(keyedBy: CodingKeys.self)
  35. try container.encode(id, forKey: .id)
  36. try container.encode(name, forKey: .name)
  37. try container.encode(target.doubleValue(for: .milligramsPerDeciliter), forKey: .targetValue)
  38. try container.encode(duration.doubleValue(for: .minute()), forKey: .durationValue)
  39. }
  40. }