Search code examples
swiftuuid

Check for UUID version in swift


Is there a way to check for UUID version? I know the UUID().uuidString is version 4. and I have a variable that comes from the server and it is in UUID version 1.

now I want to check for the version of UUID and decide for my actions.


Solution

  • Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B as described here: How to determine if a string is a valid v4 UUID?

    If you are using only version 4 and version 1 then you can do the following:

    func checkUUIDVersion(uuid: String) -> Int {
        let regx = "^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}"
        if uuid.uppercased().range(of: regx, options: .regularExpression, range: nil, locale: nil) != nil {
            return 4;
        }
        return 1;
    }