Scanning database...
Tools
Articles

No matches found for ""

View All Results
Home Dev Lab swift
Developer Lab

UUID in Swift

Production-ready implementation guide with CSPRNG-backed code snippets.



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 snippet
import Foundation

// UUID v4 — random, CSPRNG-backed, zero dependencies
let id = UUID()
print(id.uuidString)
// → "6BA7B810-9DAD-11D1-80B4-00C04FD430C8" (uppercase)

// Lowercase (many APIs expect lowercase)
let idLower = id.uuidString.lowercased()
// → "6ba7b810-9dad-11d1-80b4-00c04fd430c8"

// 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: "6BA7B810-9DAD-11D1-80B4-00C04FD430C8") {
    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 snippet
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 snippet
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 snippet
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 snippet
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 snippet
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 snippet
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 CFUUIDCreate 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

6BA7B810-9DAD-11D1-80B4-00C04FD430C8

id.uuidString.lowercased()

6ba7b810-9dad-11d1-80b4-00c04fd430c8

id.uuid — raw bytes tuple

(UInt8, UInt8, ...) — 16 bytes

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.

Installation

// 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.

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.