Human-readable file size with Swift

 

func humanReadableFileSize(bytes: Double) -> String {

    let units = ["B", "KB", "MB", "GB", "TB", "PB", "EB"]

    let prefixes = [1.0, 1000.0, 1000000.0, 1000000000.0, 1000000000000.0, 1000000000000000.0, 1000000000000000000.0]

    var size = bytes

    for (index, unit) in units.enumerated() {

        if size < prefixes[index] {

            return String(format: "%.2f %@", size, unit)

        }

        size /= prefixes[index]

    }        

    return String(format: "%.2f %@", size, units.last!)

}