Last active
January 9, 2024 15:42
-
-
Save fethica/52ef6d842604e416ccd57780c6dd28e6 to your computer and use it in GitHub Desktop.
[Swift] Convert Bytes to Kilobytes to Megabytes to Gigabytes
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
public struct Units { | |
public let bytes: Int64 | |
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 init(bytes: Int64) { | |
self.bytes = bytes | |
} | |
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" | |
} | |
} | |
} | |
print(Units(bytes: 546546546).getReadableUnit()) |
Nice! But have you checked out ByteCountFormatter
?
License?
Awesome! thanks!
Thanks
let formatted = ByteCountFormatter.string(fromByteCount: (1024 * 1024 * 8), countStyle: .file)
prints 8.4 MB
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks mate!