Skip to content

Instantly share code, notes, and snippets.

@siempay
Created September 23, 2020 09:39
Show Gist options
  • Save siempay/1dd2af4ccc06cea2858ced27d0988c21 to your computer and use it in GitHub Desktop.
Save siempay/1dd2af4ccc06cea2858ced27d0988c21 to your computer and use it in GitHub Desktop.
Swift 5: Get Binary Data size by Kb, Mb etc ...
extension Data {
var bytes: Int64 {
.init(self.count)
}
public var kilobytes: Double {
return Double(bytes) / 1_024
}
public var megabytes: Double {
return kilobytes / 1_024
}
public var gigabytes: Double {
return megabytes / 1_024
}
public func getReadableUnit() -> String {
switch bytes {
case 0..<1_024:
return "\(bytes) bytes"
case 1_024..<(1_024 * 1_024):
return "\(String(format: "%.2f", kilobytes)) kb"
case 1_024..<(1_024 * 1_024 * 1_024):
return "\(String(format: "%.2f", megabytes)) mb"
case (1_024 * 1_024 * 1_024)...Int64.max:
return "\(String(format: "%.2f", gigabytes)) gb"
default:
return "\(bytes) bytes"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment