Skip to main content

Searching...

Tools
Articles
View All Results

Developer Lab · Swift

Generate UUID in Swift

Foundation.UUID is built into Apple's frameworks - zero dependencies. UUID() generates a v4 UUID. Use .uuidString for the uppercase string, or .lowercased() when APIs expect lowercase.

Quick Reference

API Version Notes Use Case
UUID() v4 Zero deps General purpose - built-in Foundation
.uuidString v4 Uppercase Standard uppercase hyphenated string
UUID(uuidString:) any Failable init Parse - returns nil on invalid input

Primary Implementation

Production Ready
swift
import Foundation

// UUID v4 - random, CSPRNG-backed, zero dependencies
let id = UUID()
print(id.uuidString)
// → "F47AC10B-58CC-4372-A567-0E02B2C3D479" (uppercase)

// Lowercase (many APIs expect lowercase)
let idLower = id.uuidString.lowercased()
// → "f47ac10b-58cc-4372-a567-0e02b2c3d479"

// As raw bytes (16 bytes)
let idBytes: (UInt8, UInt8, UInt8, UInt8,
              UInt8, UInt8, UInt8, UInt8,
              UInt8, UInt8, UInt8, UInt8,
              UInt8, UInt8, UInt8, UInt8) = id.uuid

// Parse - failable initializer returns nil on invalid input
if let parsed = UUID(uuidString: "F47AC10B-58CC-4372-A567-0E02B2C3D479") {
    print("Parsed: \(parsed.uuidString)")
} else {
    print("Invalid UUID")
}

// Generate multiple
let ids = (0..<5).map { _ in UUID() }

All UUID Versions

UUID v4 - Random (built-in Foundation)

swift
import Foundation

let id = UUID()
print(id.uuidString)          // uppercase: "550E8400-E29B-41D4-A716-446655440000"
print(id.uuidString.lowercased()) // lowercase: "550e8400-e29b-41d4-a716-446655440000"

SwiftUI - Identifiable conformance

swift
import Foundation
import SwiftUI

struct TodoItem: Identifiable {
    let id = UUID()  // UUID conforms to Identifiable out of the box
    var title: String
    var isCompleted: Bool
}

struct TodoListView: View {
    let items: [TodoItem]

    var body: some View {
        List(items) { item in  // uses item.id (UUID) for stable identity
            Text(item.title)
        }
    }
}

CoreData - UUID attribute

swift
import CoreData

// In your .xcdatamodeld, set the attribute type to "UUID"
// CoreData maps it to Foundation.UUID natively

@NSManaged public var id: UUID

// In the managed object subclass init:
override func awakeFromInsert() {
    super.awakeFromInsert()
    id = UUID()
}

Real-World Use Cases

1. SwiftUI list item with stable identity

swift
struct Note: Identifiable, Codable {
    let id: UUID
    var content: String
    var createdAt: Date

    init(content: String) {
        self.id        = UUID()
        self.content   = content
        self.createdAt = Date()
    }
}

// SwiftUI uses id for diffing - animations work correctly
@State private var notes: [Note] = []

func addNote(_ text: String) {
    notes.append(Note(content: text))
}

2. Keychain item identifier

swift
import Security
import Foundation

func storeToken(_ token: String) throws -> UUID {
    let itemID = UUID()
    let query: [String: Any] = [
        kSecClass as String:       kSecClassGenericPassword,
        kSecAttrAccount as String: itemID.uuidString,
        kSecValueData as String:   token.data(using: .utf8)!,
    ]
    let status = SecItemAdd(query as CFDictionary, nil)
    guard status == errSecSuccess else {
        throw KeychainError.unhandledError(status: status)
    }
    return itemID // return the UUID to look up the token later
}

3. API request with idempotency key

swift
import Foundation

func createOrder(payload: OrderPayload) async throws -> Order {
    var request = URLRequest(url: URL(string: "https://api.example.com/orders")!)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    // Lowercase UUID for the idempotency key header
    request.setValue(UUID().uuidString.lowercased(), forHTTPHeaderField: "Idempotency-Key")
    request.httpBody = try JSONEncoder().encode(payload)

    let (data, _) = try await URLSession.shared.data(for: request)
    return try JSONDecoder().decode(Order.self, from: data)
}

Common Mistakes

Using .uuidString when the API expects lowercase

UUID().uuidString returns an uppercase string. Many REST APIs and databases expect lowercase UUIDs. Always use .uuidString.lowercased() when the format matters.

Force-unwrapping UUID(uuidString:)

UUID(uuidString:) is a failable initializer - it returns nil for invalid input. Force-unwrapping with ! will crash on invalid strings. Use if let or guard let.

Generating a new UUID in a SwiftUI View body

Calling UUID() inside a View body generates a new UUID on every render, breaking SwiftUI's diffing. Store the UUID in a model struct or @State property.

How It Works

UUID() calls uuid_generate_random (libSystem) under the hood, which uses the OS CSPRNG (SecRandomCopyBytes / /dev/urandom) to generate 16 random bytes, then sets the version (4) and variant bits.

UUID is a value type (struct) in Swift - copying it copies 16 bytes on the stack. It conforms to Hashable, Equatable, Codable, and Identifiable.

Output Formats

id.uuidString

F47AC10B-58CC-4372-A567-0E02B2C3D479

id.uuidString.lowercased()

f47ac10b-58cc-4372-a567-0e02b2c3d479

id.uuid - raw bytes tuple

(UInt8, UInt8, ...) - 16 bytes

Best Practices, Performance, and Security

Best practices

Store UUID values in models - only convert to string at API/DB boundaries.

Use UUID as the id property in Identifiable structs for SwiftUI.

Use .lowercased() when sending UUIDs to REST APIs or databases.

Performance

Swift generates roughly 5–10 million UUIDs/second. UUID is a value type (struct) - 16 bytes on the stack, zero heap allocation.

UUID conforms to Codable - it serializes to a string in JSON automatically, with no extra code.

Security

Entropy source: SecRandomCopyBytes / /dev/urandom on Apple platforms. Cryptographically secure.

Suitable for session tokens, Keychain item identifiers, and API keys. UUID conforms to Hashable - safe to use as dictionary keys and in sets.

Installation

UUID v4 (Foundation)

bash
// No installation needed
import Foundation

Available on iOS 6+, macOS 10.8+, watchOS 2+, tvOS 9+. Part of the Foundation framework - no Swift Package Manager dependency needed.

Frequently Asked Questions

How do I generate a UUID in Swift?

Foundation's UUID type generates a random v4 UUID with let id = UUID(); read id.uuidString for the canonical uppercase form. It is available on Apple platforms and on Linux through swift-corelibs-foundation. Foundation has no v7, so use a package such as swift-uuid for time-ordered UUIDs.

Is UUID() cryptographically secure?

Yes. UUID() uses the platform CSPRNG (operating system secure random source), suitable for session tokens, API keys, and idempotency keys. Do not use non-cryptographic random sources for security-sensitive identifiers.

What is the difference between UUID v4 and v7 in Swift?

UUID v4 (UUID() or equivalent) is fully random and not sortable. UUID v7 embeds a millisecond timestamp for chronological sorting (RFC 9562). Use v4 for general-purpose IDs; use v7 for database primary keys at scale.

Do I need to install a package for UUID generation in Swift?

No additional package is required for basic v4 generation in Swift. Check the Installation section for version-specific notes.

How do I validate a UUID string in Swift?

Use the platform's UUID parse/validation function, or test against the RFC 4122 regex: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i. Always validate external input at API boundaries.

Should I use UUIDs as database primary keys in Swift applications?

UUIDs work well as primary keys for distributed systems. Prefer native UUID/BINARY(16) column types over VARCHAR(36). For very large tables, consider UUID v7 for better B-tree insert locality.

Can I generate UUIDs in Swift without a network connection?

Yes. UUID generation uses local OS entropy sources and does not require network access. Each call is independent and thread-safe on modern platforms.

What output formats are available in Swift?

The standard hyphenated lowercase string (36 chars) is the default. Most APIs also support 32-char hex (no hyphens) and 16-byte binary formats. Use string format for APIs and binary for database storage.

What RFC standards apply to Swift UUID generation?

Version 4 UUIDs follow RFC 4122. UUID v7 follows RFC 9562 (May 2024). Ensure your chosen method produces compliant version and variant bits.

When should I avoid UUID v1?

Avoid UUID v1 in security-sensitive contexts - it embeds MAC address and timestamp information. Prefer v4 (UUID() or equivalent) unless you need legacy Cassandra timeuuid compatibility.

Key definitions

UUID
128-bit universally unique identifier, usually shown as 36 hex characters with hyphens.
CSPRNG
Cryptographically secure pseudo-random number generator - the entropy source behind secure UUID generation.
RFC 4122
IETF standard defining UUID versions 1 through 5. Version 4 is random.
RFC 9562
IETF standard adding UUID versions 6, 7, and 8. Version 7 is time-ordered.