I want to convert byte size strings like "1234kb", "100mb" or "5gb" to their actual number representation. Is there any builtin functions for this purpose?
How parse byte size strings into actual number?
Do you mean you want to extract value from the String ?
Are you sure the format is always ddddddcccc (digits followed by chars) ? Could there be a decimal point ?
I see at least 2 options:
-
extract leading characters as long as they are Int
-
write a regex (cleaner solution). Some help here: https://stackoverflow.com/questions/30342744/swift-how-to-get-integer-from-string-and-convert-it-into-integer
It seems I can use the builtin Scanner class:
public extension String {
func parseByteSize() -> UInt64? {
var n: UInt64 = 0
let scanner = Scanner(string: self)
if scanner.scanUnsignedLongLong(&n) {
if !scanner.isAtEnd {
let suffix = self[self.index(self.startIndex, offsetBy: scanner.scanLocation)...]
switch suffix.uppercased() {
case "KB":
n *= 1024
case "MB":
n *= 1024 * 1024
case "GB":
n *= 1024 * 1024 * 1024
case "TB":
n *= 1024 * 1024 * 1024 * 1024
default:
return nil
}
}
return n
}
return nil
}
}