Last active
August 29, 2015 14:21
-
-
Save victorchee/7b7fae3fb9404735ac03 to your computer and use it in GitHub Desktop.
binary unit transform
This file contains 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 enum BinaryUnit: Int { | |
case b = 0, B, KB, MB, GB, TB, PB, ZB, YB | |
} | |
public func binaryUnitTransform(value: Double, #unit: BinaryUnit) -> (value: Double, unitString: String) { | |
var raw = unit.rawValue | |
if value < 1.0 && value > 0 && unit != .b { | |
return binaryUnitTransform(value * 1024.0, unit: BinaryUnit(rawValue: --raw)!) | |
} else if value > 1024.0 && unit != .YB { | |
return binaryUnitTransform(value / 1024.0, unit: BinaryUnit(rawValue: ++raw)!) | |
} else { | |
let units = ["\(BinaryUnit.b.rawValue)":"b", | |
"\(BinaryUnit.B.rawValue)":"B", | |
"\(BinaryUnit.KB.rawValue)":"KB", | |
"\(BinaryUnit.MB.rawValue)":"MB", | |
"\(BinaryUnit.GB.rawValue)":"GB", | |
"\(BinaryUnit.TB.rawValue)":"TB", | |
"\(BinaryUnit.PB.rawValue)":"PB", | |
"\(BinaryUnit.ZB.rawValue)":"ZB", | |
"\(BinaryUnit.YB.rawValue)":"YB"] | |
return (value, units["\(raw)"]!) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment