Skip to main content

How to Generate UUID in Swift

Using Foundation's UUID struct

Swift's Foundation framework ships a built-in UUID struct that hands you a random v4 identifier with zero third-party dependencies — call UUID() and get an RFC 4122-compliant value immediately, without installing anything. You'll reach for it constantly: SwiftUI's Identifiable conformance, Core Data primary keys, and API payload IDs across iOS, macOS, watchOS, and tvOS all lean on the same struct. Below you'll find copy-paste ready code for generating a Swift UUID, converting a string back into a UUID, and the third-party options developers reach for when Foundation's v4-only support isn't enough. The rust uuid generator reference explains how to generate v4 and v7 UUIDs with Rust's ownership-safe uuid crate.

Generate UUID in Swift

UUID()
550E8400-E29B-41D4-A716-446655440000

How to Generate a UUID in Swift

Foundation's UUID struct handles UUID generation in Swift out of the box — call UUID() to get a random, RFC 4122-compliant v4 identifier with no package manager and no configuration. The kotlin uuid page covers UUID primary keys in Exposed table definitions and JPA annotations in Spring.

UUIDExample.swift
import Foundation

let myUUID = UUID()
print(myUUID.uuidString)
// Output: 550E8400-E29B-41D4-A716-446655440000

Explanation

Convert a String to a UUID in Swift

Sometimes a UUID arrives as a string — from a network response, a config file, or user input — and you need to parse it back into a proper UUID value. Swift's UUID(uuidString:) initializer is failable, returning an optional UUID? instead of throwing, so invalid input never crashes your app. The powershell uuid reference explains the difference between [System.Guid]::NewGuid() and [guid]::NewGuid().

UUIDExample.swift
import Foundation

let uuidString = "550e8400-e29b-41d4-a716-446655440000"

guard let parsedUUID = UUID(uuidString: uuidString) else {
    fatalError("Invalid UUID string")
}
print(parsedUUID.uuidString)

Explanation

Other Options for Generating UUIDs in Swift

Foundation's UUID only generates version 4 identifiers — there's no built-in support for v1 or v7. Developers who need other UUID versions typically reach for a third-party Swift package from the Swift Package Index, or implement RFC 9562's v7 algorithm manually.

UUIDExample.swift
import Foundation

// NSUUID is the Objective-C-bridged equivalent of UUID,
// useful for interop with older Objective-C codebases
let legacyUUID = NSUUID()
let bridgedUUID = legacyUUID as UUID

print(bridgedUUID.uuidString)

Explanation

Comments & Feedback

Share your experience or ask questions about this tool

Copied!