HKUnit+Extensions.swift 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. //
  2. // HKUnit+Extensions.swift
  3. // LoopFollow
  4. //
  5. // Created by Jonas Björkert on 2024-07-15.
  6. // Copyright © 2024 Jon Fawcett. All rights reserved.
  7. //
  8. import Foundation
  9. import HealthKit
  10. extension HKUnit {
  11. public static let milligramsPerDeciliter: HKUnit = {
  12. return HKUnit.gramUnit(with: .milli).unitDivided(by: .literUnit(with: .deci))
  13. }()
  14. public static let millimolesPerLiter: HKUnit = {
  15. return HKUnit.moleUnit(with: .milli, molarMass: HKUnitMolarMassBloodGlucose).unitDivided(by: .liter())
  16. }()
  17. var preferredFractionDigits: Int {
  18. switch self {
  19. case .minute():
  20. return 0
  21. case .milligramsPerDeciliter:
  22. return 0
  23. case .millimolesPerLiter:
  24. return 1
  25. default:
  26. return 0
  27. }
  28. }
  29. var localizedShortUnitString: String {
  30. if self == HKUnit.millimolesPerLiter {
  31. return NSLocalizedString("mmol/L", comment: "The short unit display string for millimoles of glucose per liter")
  32. } else if self == .milligramsPerDeciliter {
  33. return NSLocalizedString("mg/dL", comment: "The short unit display string for milligrams of glucose per decilter")
  34. } else if self == .internationalUnit() {
  35. return NSLocalizedString("U", comment: "The short unit display string for international units of insulin")
  36. } else if self == .gram() {
  37. return NSLocalizedString("g", comment: "The short unit display string for grams")
  38. } else {
  39. return String(describing: self)
  40. }
  41. }
  42. }