19

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.

Community
  • 1
  • 1
danialzahid94
  • 4,103
  • 2
  • 19
  • 31
  • What is it you want to generate keys for? – GoatInTheMachine Jul 29 '15 at 13:45
  • For future searchers, the [hashids](http://hashids.org/swift/) library now has a version for Swift. It does just what you want - generate short, unique, non-sequential ids from integers. – wardw Jul 27 '17 at 14:04

8 Answers8

23

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

Ben
  • 3,832
  • 1
  • 29
  • 30
MrHaze
  • 3,786
  • 3
  • 26
  • 47
12

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.

Community
  • 1
  • 1
Reid
  • 734
  • 8
  • 15
5

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...!

Kiran Jadhav
  • 3,209
  • 26
  • 29
3

Does NSUUID().UUIDString do what you need?

GoatInTheMachine
  • 3,583
  • 3
  • 25
  • 35
  • 3
    As right as you are, I actually need a short ID as mentioned. Like the YouTube IDs, or the tiny URLs. Around 4-10 characters which users can easily share with others verbally. – danialzahid94 Jul 29 '15 at 13:39
1

I'm very pleased with NanoID.

https://github.com/ai/nanoid

...and here's the SWIFT version:

https://github.com/antiflasher/NanoID

You just need to drag 1 file (NanoID.swift) into your project, and you are good to go!

TAGS: Short GUID, Short UUID, Short Unique ID, Swift, iOS

Richard H
  • 300
  • 7
  • 15
0

Swift custom alternative(these version doesn't check for duplicate char):

func randomString(length: Int) -> String {
    let letters = Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
    var randomString: String = ""
    for _ in 0..<length {
        let randomNumber = Int.random(in: 0..<letters.count)
        randomString.append(letters[randomNumber])
    }
    return randomString
}
Laur Stefan
  • 1,519
  • 5
  • 23
  • 50
0

You can archive this just using UUID.

If you don't want the whole string, as any String in Swift, you select a small portion of the string by using range, like this:

let text = UUID().uuidString
let index = text.index(text.startIndex, offsetBy: 8)
let small = text[text.startIndex..<index]

Notice 8 is the length of string I suggested, you can improve this by clamping this value using min(size, text.count) for example.

And finally, small is a Substring, to cast it to String just cast as usual - String(small)

Jan Cássio
  • 2,076
  • 29
  • 41
0

Swift 5 version using a String extension

extension String {
    static func random(length: Int) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

        return String((0..<length).compactMap { _ in 
            letters.randomElement()
        })
    }
}
falcorn
  • 21
  • 4