Skip to content

Instantly share code, notes, and snippets.

@jacobd
Created December 11, 2020 19:36
Show Gist options
  • Save jacobd/691bfd3d1d66995b76e77e932158a968 to your computer and use it in GitHub Desktop.
Save jacobd/691bfd3d1d66995b76e77e932158a968 to your computer and use it in GitHub Desktop.
FileSize struct with Double extension
import Foundation
//
struct FileSize {
enum Unit: Int {
case b = 0, kb, mb, gb, tb, pb, eb, zb, yb
}
var bytes: Int = 0
init(_ bytes: Int) {
self.bytes = bytes
}
func human(as unit: Unit) -> String {
let suffixes = ["B", "K", "M", "G", "T", "P", "E", "Z", "Y"]
let exp = unit.rawValue
let suffix = suffixes[exp]
let val = Double(bytes) / pow(1024.0, Double(exp))
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 1
let formattedValue = formatter.string(from: NSNumber(value: val)) ?? "0"
return "\(formattedValue)\(suffix)"
}
subscript(unit: Unit) -> Double {
(Double(bytes) / pow(1024.0, Double(unit.rawValue)))
}
}
extension Double {
var b: FileSize { return FileSize(Int(self ))}
var bytes: FileSize { b }
var kb: FileSize { return FileSize(Int(self * pow(1024, 1)))}
var kilobytes: FileSize { kb }
var mb: FileSize { return FileSize(Int(self * pow(1024, 2)))}
var megabytes: FileSize { mb }
var gb: FileSize { return FileSize(Int(self * pow(1024, 3)))}
var gigabytes: FileSize { gb }
var tb: FileSize { return FileSize(Int(self * pow(1024, 4)))}
var terabytes: FileSize { tb }
var pb: FileSize { return FileSize(Int(self * pow(1024, 5)))}
var petabytes: FileSize { pb }
var eb: FileSize { return FileSize(Int(self * pow(1024, 6)))}
var exobytes: FileSize { eb }
var zb: FileSize { return FileSize(Int(self * pow(1024, 7)))}
var zettabytes: FileSize { zb }
var yb: FileSize { return FileSize(Int(self * pow(1024, 8)))}
var yottabytes: FileSize { yb }
}
2.gb.human(as: .mb)
64087267.b.human(as: .mb)
1504.21.petabytes.human(as: .mb)
1.tb[.mb]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment