GlucoseThreshold.swift 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. public func convertTo(unit: HKUnit) -> GlucoseThreshold {
  35. guard unit != self.unit else {
  36. return self
  37. }
  38. let convertedValue = self.quantity.doubleValue(for: unit)
  39. return GlucoseThreshold(unit: unit,
  40. value: convertedValue)
  41. }
  42. }
  43. extension GlucoseThreshold: Codable {
  44. public init(from decoder: Decoder) throws {
  45. let container = try decoder.container(keyedBy: CodingKeys.self)
  46. self.value = try container.decode(Double.self, forKey: .value)
  47. self.unit = HKUnit(from: try container.decode(String.self, forKey: .unit))
  48. }
  49. public func encode(to encoder: Encoder) throws {
  50. var container = encoder.container(keyedBy: CodingKeys.self)
  51. try container.encode(value, forKey: .value)
  52. try container.encode(unit.unitString, forKey: .unit)
  53. }
  54. private enum CodingKeys: String, CodingKey {
  55. case value
  56. case unit
  57. }
  58. }