GlucoseThreshold.swift 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. //
  2. // GlucoseThreshold.swift
  3. // Loop
  4. //
  5. // Created by Pete Schwamb on 1/1/17.
  6. // Copyright © 2017 LoopKit Authors. All rights reserved.
  7. //
  8. import Foundation
  9. import HealthKit
  10. public struct GlucoseThreshold: Equatable, RawRepresentable {
  11. public typealias RawValue = [String: Any]
  12. public let value: Double
  13. public let unit: HKUnit
  14. public var quantity: HKQuantity {
  15. return HKQuantity(unit: unit, doubleValue: value)
  16. }
  17. public init(unit: HKUnit, value: Double) {
  18. self.value = value
  19. self.unit = unit
  20. }
  21. public init?(rawValue: RawValue) {
  22. guard let unitsStr = rawValue["units"] as? String, let value = rawValue["value"] as? Double else {
  23. return nil
  24. }
  25. self.unit = HKUnit(from: unitsStr)
  26. self.value = value
  27. }
  28. public var rawValue: RawValue {
  29. return [
  30. "value": value,
  31. "units": unit.unitString
  32. ]
  33. }
  34. }
  35. extension GlucoseThreshold: Codable {
  36. public init(from decoder: Decoder) throws {
  37. let container = try decoder.container(keyedBy: CodingKeys.self)
  38. self.value = try container.decode(Double.self, forKey: .value)
  39. self.unit = HKUnit(from: try container.decode(String.self, forKey: .unit))
  40. }
  41. public func encode(to encoder: Encoder) throws {
  42. var container = encoder.container(keyedBy: CodingKeys.self)
  43. try container.encode(value, forKey: .value)
  44. try container.encode(unit.unitString, forKey: .unit)
  45. }
  46. private enum CodingKeys: String, CodingKey {
  47. case value
  48. case unit
  49. }
  50. }