How to generate UUID in the swift example
There are multiple ways to generate UUID in swift with examples.
- NSUUID()🔗 class
- UUID🔗 structure
Unique identifiers are 128-bit values that store unique values.
There are different types of aliases
- Universally Unique Identifier(UUID)
- Globally Unique Identifiers(GUID)
- Interface Identifiers(IID)
These unique identifiers are used to represent the primary key of an object in the database
UUID follows RFC 4122 Version2 always generates a Unique string in lower case.
These are written with base 16, and use 1-9 and a-f characters.
Generate UUID in swift with example
- using
NSUUID
class
NSUUID
class provides uuidString
that returns the unique string in uppercase.
import Foundation
let uuid = NSUUID().uuidString
print(uuid) //09BA1C5D-71CE-4DD8-BBF4-4099FD68705A
NSUUID
works in the swift 4 version only.
- using
UUID
Structure
uuidString
method of UUID
returns a unique string
Here is an example
import Foundation
let uuid1 = UUID().uuidString
print(uuid1)//770C0441-121B-438F-8058-AFE452BFF047
Summary
To summarize, Unique strings are a common requirement in every programming language. Swift provides a default API to generate it.