How to Generate UUID in Swift

Using Foundation's UUID struct

Generate UUIDs in Swift using Foundation's built-in UUID struct. No external dependencies needed - works seamlessly across iOS, macOS, watchOS, and tvOS with native SwiftUI and Core Data integration.

Generate UUID in Swift

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

Generate UUID with Foundation Framework

Swift's UUID struct is part of Foundation framework, available on all Apple platforms without any imports or dependencies. Simply create a UUID() instance to generate a random UUID v4 with cryptographic randomness guaranteed by the system.

Built into Foundation

No imports needed! UUID is available by default in all Swift applications on Apple platforms.

import Foundation

// Generate random UUID (v4)
let uuid = UUID()
print(uuid)  // 550E8400-E29B-41D4-A716-446655440000

UUID String Formatting Options

Swift UUIDs are uppercase by default. Access the UUID as a string using the uuidString property, and convert to lowercase if needed for compatibility with other systems or APIs that expect lowercase formatting.

UUIDExample.swift
import Foundation

// Generate UUID
let uuid = UUID()
print(uuid)  
// 550E8400-E29B-41D4-A716-446655440000

// Get as string (uppercase by default)
let upperString = uuid.uuidString
print(upperString)  
// "550E8400-E29B-41D4-A716-446655440000"

// Get as lowercase
let lowerString = uuid.uuidString.lowercased()
print(lowerString)  
// "550e8400-e29b-41d4-a716-446655440000"

// Generate multiple UUIDs
let uuids = (0..<5).map { _ in UUID() }
uuids.forEach { print($0) }

Parse and Validate UUID Strings

Swift's UUID initializer accepts string representations and returns an optional UUID, providing safe parsing without throwing exceptions. Use optional binding to gracefully handle invalid UUID strings from user input or external APIs.

Optional Binding

// Parse from string (optional)
if let parsed = UUID(uuidString: "550e8400-e29b-41d4-a716-446655440000") {
    print("Valid: \(parsed)")
} else {
    print("Invalid UUID")
}

// Force unwrap (use with caution)
let uuid = UUID(uuidString: "550e8400-e29b-41d4-a716-446655440000")!

Comparison

// Compare UUIDs
let uuid1 = UUID()
let uuid2 = UUID()

if uuid1 == uuid2 {
    print("Same UUID")
} else {
    print("Different UUIDs")
}

// Usually different (random)

SwiftUI Identifiable Protocol Integration

Use UUID with SwiftUI's Identifiable protocol to create stable, unique identifiers for list items. This ensures ForEach views update correctly and animations work smoothly when list data changes.

TodoItem.swift
import SwiftUI

struct TodoItem: Identifiable {
    let id = UUID()  // Auto-generated UUID
    var title: String
    var isComplete: Bool
}

struct ContentView: View {
    @State private var items = [
        TodoItem(title: "Buy groceries", isComplete: false),
        TodoItem(title: "Call dentist", isComplete: true),
        TodoItem(title: "Finish project", isComplete: false)
    ]
    
    var body: some View {
        List {
            ForEach(items) { item in
                HStack {
                    Text(item.title)
                    Spacer()
                    if item.isComplete {
                        Image(systemName: "checkmark.circle.fill")
                            .foregroundColor(.green)
                    }
                }
            }
        }
    }
}

Core Data UUID Attributes

Core Data supports UUID attributes natively, providing efficient storage and indexing for UUID primary keys. Use @NSManaged properties with UUID type for seamless integration with Core Data's managed object context.

Item+CoreDataClass.swift
import Foundation
import CoreData

@objc(Item)
public class Item: NSManagedObject {
    @NSManaged public var id: UUID?
    @NSManaged public var name: String?
    @NSManaged public var createdAt: Date?
}

// Create with UUID
extension Item {
    static func create(in context: NSManagedObjectContext, name: String) -> Item {
        let item = Item(context: context)
        item.id = UUID()
        item.name = name
        item.createdAt = Date()
        return item
    }
}

// Usage
let viewContext = persistentContainer.viewContext
let newItem = Item.create(in: viewContext, name: "Example Item")
try? viewContext.save()

Codable Support for JSON Serialization

UUID conforms to Codable protocol automatically, enabling seamless JSON encoding and decoding. This makes UUIDs perfect for REST API communication, local storage, and data persistence in Swift applications.

User.swift
import Foundation

struct User: Codable {
    let id: UUID
    let name: String
    let email: String
}

// Create user with UUID
let user = User(
    id: UUID(),
    name: "Alice",
    email: "alice@example.com"
)

// Encode to JSON
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted

if let jsonData = try? encoder.encode(user),
   let jsonString = String(data: jsonData, encoding: .utf8) {
    print(jsonString)
    /*
    {
      "id" : "550E8400-E29B-41D4-A716-446655440000",
      "name" : "Alice",
      "email" : "alice@example.com"
    }
    */
}

// Decode from JSON
let decoder = JSONDecoder()
if let decodedUser = try? decoder.decode(User.self, from: jsonData) {
    print("Decoded: \(decodedUser.id)")
}

Related Programming Language UUID Guides

Copied!