{

How to generate UUID in the swift example


There are multiple ways to generate UUID in swift with examples.

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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.