Created
September 23, 2020 09:39
-
-
Save siempay/1dd2af4ccc06cea2858ced27d0988c21 to your computer and use it in GitHub Desktop.
Swift 5: Get Binary Data size by Kb, Mb etc ...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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