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"
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 {
/// ...
}
UUID conforms 4 protocols:
Also, the structure has some properties:
- 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 }
- uuidString - Returns a string created from the UUID, such as âE621E1F8-C36C-495A-93FC-0C247A3E6E5Fâ
var uuidString: String { get }
Thanks for reading! See you soon. đ