Is there a way to create random unique IDs similar to the YouTube IDs in Swift?
I know there are similar answers on this link, but they are for Php. But I want something in Swift.
I have tried using timestamp and UUIDs, but I want an alphanumeric short keys which would be around 4-10 characters so users can easily share with others verbally.
Thanks.
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.
UUIDKit is a Swift library for generating and working with Universally Unique Identifiers (UUIDs) as specified in RFC 4122.
Individuals and organizations can create GUIDs using a free GUID generator that is available online. An online generator constructs a unique GUID according to RFC 4122. When creating a GUID, users should note the timestamp, clock sequence and the node ID -- such as a Media Access Control (MAC) address.
The simplest way to generate identifiers is by a serial number. A steadily increasing number that is assigned to whatever you need to identify next. This is the approached used in most internal databases as well as some commonly encountered public identifiers.
You can use UUIDs they're pretty cool:
let uuid = NSUUID().UUIDString
print(uuid)
From the docs
UUIDs (Universally Unique Identifiers), also known as GUIDs (Globally Unique Identifiers) or IIDs (Interface Identifiers), are 128-bit values. UUIDs created by NSUUID conform to RFC 4122 version 4 and are created with random bytes.
Some info about uuid: https://en.wikipedia.org/wiki/Universally_unique_identifier
Try something like this:
func randomStringWithLength(len: Int) -> NSString {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let randomString : NSMutableString = NSMutableString(capacity: len)
for _ in 1...len{
let length = UInt32 (letters.length)
let rand = arc4random_uniform(length)
randomString.appendFormat("%C", letters.character(at: Int(rand)))
}
return randomString
}
But i'll keep my answer incase someone else stumbles upon this looking for a UUID
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