TempTargetPreset.swift 1.5 KB

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