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

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


Updated for swift 3:

If you want to generate Short Random Unique alphanumeric keys, used below lines of codes;

//function defination:

func generateTransactionId(length: Int) -> String {
    var result = ""
    let base62chars = [Character]("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".characters)
    let maxBase : UInt32 = 62
    let minBase : UInt16 = 32

    for _ in 0..<length {
        let random = Int(arc4random_uniform(UInt32(min(minBase, UInt16(maxBase)))))
        result.append(base62chars[random])
    }
    return result
}

//function call:

let mTranactionId = self.generateTransactionId(length: 5) // you can change the value of length as you want
print("mTranactionId: \(mTranactionId)")

Ex: Result looks like: XHA7K, QTC92, MS1PT, YE2PV

//Enjoy coding...!


This will allow you to create a random short code. It can create codes from Hexadecimal all the way to base 62 codes and of varying lengths.

aka.

let myCode = ShortCodeGenerator.getCode(length: 6)

3dH7t8, fdE7j1, Gl6jKd, Hv8gU3,

let myBase32Code = ShortCodeGenerator.getCode(withBase: UInt32(32), length: 6)

3HF75J, J67N9D, B47SO3, L9SD2N

You would have to check for redundancy and then create a new one if it has already been used.

struct ShortCodeGenerator {

    private static let base62chars = [Character]("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".characters)
    private static let maxBase : UInt32 = 62

    static func getCode(withBase base: UInt32 = maxBase, length: Int) -> String {
        var code = ""
        for _ in 0..<length {
            let random = Int(arc4random_uniform(min(base, maxBase)))
            code.append(base62chars[random])
        }
        return code
    }
}

This answer was useful in creating the above code and also has good information on the number of unique identifiers you can have with each base number and length.

The total number of unique identifiers you need can be calculated by the equation:

BaseNumber^length = # of unique IDs

EDIT:

I have added even more functionality for converting Int's and NSDate's to shortcodes for my own project as well and put those into a project on GitHub.