Given an supplied String
, how can I verify wether the String
is a valid UUID in Swift?
A valid UUID (as far as I know) could be:
33041937-05b2-464a-98ad-3910cbe0d09e 3304193705b2464a98ad3910cbe0d09e
A valid UUID should have 5 sections separated by a dash ( - ) and in the first section it should have 8 characters, the second, third, and the fourth section should have 4 characters each, and the last section should have 12 characters with a total of 32 characters.
UUIDs support input of case-insensitive string literal formats, as specified by RFC 4122. In general, a UUID is written as a sequence of hexadecimal digits, in several groups optionally separated by hyphens, for a total of 32 digits representing 128 bits.
In Swift, we can generate UUIDs with the UUID struct. The UUID() initializer generates 128 random bits. Because the UUID struct conforms to the CustomStringConvertible, we can print it as a string.
UUID is a simple structure, which has the property uuidString . uuidString - returns a string created from the UUID, such as “E621E1F8-C36C-495A-93FC-0C247A3E6E5F”. UUID is guaranteed to be unique. Swift code: let identifier = UUID().uuidString Swift.print(identifier) // Result: "6A967474-8672-4ABC-A57B-52EA809C5E6D"
You could use UUID
var uuid = UUID(uuidString: yourString)
This will return nil if yourString
is not a valid UUID
Note: this only validates the first case you presented, not the second but adding the dashes yourself is trivial.
The following is updated for Swift 4.0 to determine if a string is a valid UUID.
let uuidHyphens = "33041937-05b2-464a-98ad-3910cbe0d09e" let uuidNoHyphens = "3304193705b2464a98ad3910cbe0d09e" if UUID(uuidString: uuidHyphens) != nil { print("UUID string with hypens is valid") // Will be valid } else { print("UUID string with hypens is not valid") } // In this scenario, the UUID will be nil, if UUID(uuidString: uuidNoHyphens) != nil { print("UUID string with no hypens is valid") } else { print("UUID string with no hypens is not valid") // Will not be valid }
The string passed in to the UUID init must contain hyphens, otherwise the check will fail. If you are expecting strings without hypens, then you can utilize an approach such as what is discussed here to add hypens to a string if it satisfies a length of 32.
The relevant section from Apple's documentation:
Create a UUID from a string such as “E621E1F8-C36C-495A-93FC-0C247A3E6E5F”.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With