Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short Random Unique alphanumeric keys similar to Youtube IDs, in Swift

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.

like image 967
danialzahid94 Avatar asked Jul 29 '15 13:07

danialzahid94


People also ask

How do I get a random unique ID in Swift?

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.

What is a UUID in Swift?

UUIDKit is a Swift library for generating and working with Universally Unique Identifiers (UUIDs) as specified in RFC 4122.

How do I make a global unique identifier?

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.

How do I get a unique identifier code?

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.


1 Answers

Looking for just a unique string

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

Looking for a more specific length

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

like image 103
MrHaze Avatar answered Sep 16 '22 12:09

MrHaze