How parse byte size strings into actual number?

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?

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:

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
    }
}
How parse byte size strings into actual number?
 
 
Q