Units.swift 897 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //
  2. // Units.swift
  3. // NexilisLite
  4. //
  5. // Created by Akhmad Al Qindi Irsyam on 20/02/23.
  6. //
  7. import Foundation
  8. public struct Units {
  9. public let bytes: Int64
  10. public var kilobytes: Double {
  11. return Double(bytes) / 1_024
  12. }
  13. public var megabytes: Double {
  14. return kilobytes / 1_024
  15. }
  16. public var gigabytes: Double {
  17. return megabytes / 1_024
  18. }
  19. public init(bytes: Int64) {
  20. self.bytes = bytes
  21. }
  22. public func getReadableUnit() -> String {
  23. switch bytes {
  24. case 0..<1_024:
  25. return "\(bytes) Bytes"
  26. case 1_024..<(1_024 * 1_024):
  27. return "\(String(format: "%.2f", kilobytes)) KB"
  28. case 1_024..<(1_024 * 1_024 * 1_024):
  29. return "\(String(format: "%.2f", megabytes)) MB"
  30. case (1_024 * 1_024 * 1_024)...Int64.max:
  31. return "\(String(format: "%.2f", gigabytes)) GB"
  32. default:
  33. return "\(bytes) Bytes"
  34. }
  35. }
  36. }