DEV Community

Cover image for How to generate a random unique identifier with UUID
Anton Paliakou
Anton Paliakou

Posted on

3 1

How to generate a random unique identifier with UUID

UUID is a universally unique identifier. UUID can be used to identify types, interfaces, and other items.
Creating an object or some entity with an unique identifier is a common task for developers. UUID structure created for to do this and to do it best, do not need create "bicycle".
UUID is guaranteed to be unique. When initializing the structure, a new UUID is created with RFC 4122 version 4 random bytes.

import Foundation

let identifier = UUID().uuidString
Swift.print(identifier) // Result: "6A967474-8672-4ABC-A57B-52EA809C5E6D" 
Enter fullscreen mode Exit fullscreen mode

Available iOS 6.0+, macOS 10.8+, tvOS 9.0+, watchOS 2.0+.

What's UUID from a code perspective?

UUID is a simple structure and is a part of Foundation framework.

public struct UUID: ReferenceConvertible, Hashable, Equatable, CustomStringConvertible {
  /// ...
}
Enter fullscreen mode Exit fullscreen mode

UUID conforms 4 protocols:

Also, the structure has some properties:

1 uuid - Returns the UUID as bytes.

var uuid: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) { get } 
Enter fullscreen mode Exit fullscreen mode

2 uuidString - Returns a string created from the UUID, such as “E621E1F8-C36C-495A-93FC-0C247A3E6E5F”

var uuidString: String { get }
Enter fullscreen mode Exit fullscreen mode

Articles comes to devto portal with delay 1-2 week, if you want read my articles without delay you can visit ToniDevBlog

Article originally published at ToniDevBlog

Thanks for reading! See you soon. 👋

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs