HKUnit.swift 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import HealthKit
  2. extension HKUnit {
  3. static let milligramsPerDeciliter: HKUnit = {
  4. HKUnit.gramUnit(with: .milli).unitDivided(by: .literUnit(with: .deci))
  5. }()
  6. static let millimolesPerLiter: HKUnit = {
  7. HKUnit.moleUnit(with: .milli, molarMass: HKUnitMolarMassBloodGlucose).unitDivided(by: .liter())
  8. }()
  9. static let internationalUnitsPerHour: HKUnit = {
  10. HKUnit.internationalUnit().unitDivided(by: .hour())
  11. }()
  12. static let gramsPerUnit: HKUnit = {
  13. HKUnit.gram().unitDivided(by: .internationalUnit())
  14. }()
  15. var foundationUnit: Unit? {
  16. if self == HKUnit.milligramsPerDeciliter {
  17. return UnitConcentrationMass.milligramsPerDeciliter
  18. }
  19. if self == HKUnit.millimolesPerLiter {
  20. return UnitConcentrationMass.millimolesPerLiter(withGramsPerMole: HKUnitMolarMassBloodGlucose)
  21. }
  22. if self == HKUnit.gram() {
  23. return UnitMass.grams
  24. }
  25. return nil
  26. }
  27. /// The smallest value expected to be visible on a chart
  28. var chartableIncrement: Double {
  29. if self == .milligramsPerDeciliter {
  30. return 1
  31. } else {
  32. return 1 / 25
  33. }
  34. }
  35. var localizedShortUnitString: String {
  36. if self == HKUnit.millimolesPerLiter {
  37. return NSLocalizedString("mmol/L", comment: "The short unit display string for millimoles of glucose per liter")
  38. } else if self == .milligramsPerDeciliter {
  39. return NSLocalizedString("mg/dL", comment: "The short unit display string for milligrams of glucose per decilter")
  40. } else if self == .internationalUnit() {
  41. return NSLocalizedString("U", comment: "The short unit display string for international units of insulin")
  42. } else if self == .gram() {
  43. return NSLocalizedString("g", comment: "The short unit display string for grams")
  44. } else {
  45. return String(describing: self)
  46. }
  47. }
  48. }