Generate a UUID on iOS from Swift

IosSwiftCocoa TouchGuidCore Foundation

Ios Problem Overview


In my iOS Swift app I want to generate random UUID (GUID) strings for use as a table key, and this snippet appears to work:

let uuid = CFUUIDCreateString(nil, CFUUIDCreate(nil))

Is this safe?

Or is there perhaps a better (recommended) approach?

Ios Solutions


Solution 1 - Ios

Try this one:

let uuid = NSUUID().uuidString
print(uuid)

Swift 3/4/5

let uuid = UUID().uuidString
print(uuid)

Solution 2 - Ios

You could also just use the NSUUID API:

let uuid = NSUUID()

If you want to get the string value back out, you can use uuid.UUIDString.

Note that NSUUID is available from iOS 6 and up.

Solution 3 - Ios

For Swift 4;

let uuid = NSUUID().uuidString.lowercased()

Solution 4 - Ios

For Swift 3, many Foundation types have dropped the 'NS' prefix, so you'd access it by UUID().uuidString.

Solution 5 - Ios

Also you can use it lowercase under below

let uuid = NSUUID().UUIDString.lowercaseString
print(uuid)

Output >68b696d7-320b-4402-a412-d9cee10fc6a3

Thank you !

Solution 6 - Ios

Each time the same will be generated:

if let uuid = UIDevice.current.identifierForVendor?.uuidString {
    print(uuid)
}

Each time a new one will be generated:

let uuid = UUID().uuidString
print(uuid)

Solution 7 - Ios

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"

Apple official documentation about UUID.
Full article https://tonidevblog.com/posts/how-to-generate-a-random-unique-identifier-with-uuid/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzacjordaanView Question on Stackoverflow
Solution 1 - IosAhmed Al HafoudhView Answer on Stackoverflow
Solution 2 - IosJames FrostView Answer on Stackoverflow
Solution 3 - IosCelil BozkurtView Answer on Stackoverflow
Solution 4 - IosScott HView Answer on Stackoverflow
Solution 5 - IosSwiftDeveloperView Answer on Stackoverflow
Solution 6 - IosiAleksandrView Answer on Stackoverflow
Solution 7 - IosAnton PolyakovView Answer on Stackoverflow