Skip to content

Generate UUID in Swift

Swift provides built-in UUID generation through the Foundation framework. The simplest way to generate a UUID is using the UUID() initializer:

swift
import Foundation

// Generate UUID version 4 - random
let uuid = UUID()
print("Generated UUID: \(uuid.uuidString)")

// Alternative using NSUUID (Objective-C compatibility)
let nsUuid = NSUUID()
print("NSUUID: \(nsUuid.uuidString)")

Swift's Foundation framework primarily supports UUID version 4 (random). For other UUID versions, you may need third-party libraries or custom implementations:

swift
import Foundation

class UUIDGenerator {
    
    // Generate UUID version 4 - random (built-in)
    static func generateV4() -> String {
        return UUID().uuidString
    }
    
    // Generate UUID version 1 - time based (custom implementation)
    static func generateV1() -> String {
        // Note: This is a simplified implementation
        // For production use, consider a proper UUID v1 library
        let timestamp = UInt64(Date().timeIntervalSince1970 * 1000000)
        let uuid = UUID()
        return uuid.uuidString // Placeholder - would need proper v1 implementation
    }
    
    // Generate UUID version 3 - MD5 namespace (custom implementation)
    static func generateV3(namespace: String, name: String) -> String {
        // Note: Requires custom MD5 implementation
        // For production use, consider CryptoKit or third-party library
        return UUID().uuidString // Placeholder
    }
    
    // Generate UUID version 5 - SHA1 namespace (custom implementation)
    static func generateV5(namespace: String, name: String) -> String {
        // Note: Requires custom SHA1 implementation
        // For production use, consider CryptoKit or third-party library
        return UUID().uuidString // Placeholder
    }
}

// Usage
let uuid4 = UUIDGenerator.generateV4()
print("UUID v4: \(uuid4)")

iOS/macOS Development Usage

Core Data Integration:

swift
import CoreData
import Foundation

@objc(User)
public class User: NSManagedObject {
    
    @NSManaged public var id: UUID
    @NSManaged public var name: String
    @NSManaged public var createdAt: Date
    
    override public func awakeFromInsert() {
        super.awakeFromInsert()
        self.id = UUID()
        self.createdAt = Date()
    }
}

SwiftUI Integration:

swift
import SwiftUI

struct ContentView: View {
    @State private var currentUUID = UUID().uuidString
    
    var body: some View {
        VStack(spacing: 20) {
            Text("UUID Generator")
                .font(.title)
            
            Text(currentUUID)
                .font(.system(.body, design: .monospaced))
                .padding()
                .background(Color.gray.opacity(0.1))
                .cornerRadius(8)
            
            Button("Generate New UUID") {
                currentUUID = UUID().uuidString
            }
            .buttonStyle(.borderedProminent)
        }
        .padding()
    }
}

Networking & API Integration:

swift
import Foundation

struct APIRequest {
    let id: UUID
    let endpoint: String
    let timestamp: Date
    
    init(endpoint: String) {
        self.id = UUID()
        self.endpoint = endpoint
        self.timestamp = Date()
    }
    
    var headers: [String: String] {
        return [
            "X-Request-ID": id.uuidString,
            "Content-Type": "application/json"
        ]
    }
}

// Usage
let request = APIRequest(endpoint: "/api/users")
print("Request ID: \(request.id.uuidString)")

Advanced Swift UUID Usage

UUID Validation and Parsing:

swift
import Foundation

extension UUID {
    
    // Validate UUID string format
    static func isValid(_ uuidString: String) -> Bool {
        return UUID(uuidString: uuidString) != nil
    }
    
    // Parse UUID from string with error handling
    static func parse(_ uuidString: String) -> Result<UUID, UUIDError> {
        guard let uuid = UUID(uuidString: uuidString) else {
            return .failure(.invalidFormat)
        }
        return .success(uuid)
    }
}

enum UUIDError: Error, LocalizedError {
    case invalidFormat
    
    var errorDescription: String? {
        switch self {
        case .invalidFormat:
            return "Invalid UUID format"
        }
    }
}

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

if UUID.isValid(uuidString) {
    print("Valid UUID")
}

switch UUID.parse(uuidString) {
case .success(let uuid):
    print("Parsed UUID: \(uuid)")
case .failure(let error):
    print("Error: \(error.localizedDescription)")
}

Codable Support:

swift
import Foundation

struct User: Codable {
    let id: UUID
    let name: String
    let email: String
    
    init(name: String, email: String) {
        self.id = UUID()
        self.name = name
        self.email = email
    }
}

// JSON encoding/decoding works automatically
let user = User(name: "John Doe", email: "[email protected]")

do {
    let jsonData = try JSONEncoder().encode(user)
    let jsonString = String(data: jsonData, encoding: .utf8)
    print("JSON: \(jsonString ?? "")")
    
    let decodedUser = try JSONDecoder().decode(User.self, from: jsonData)
    print("Decoded ID: \(decodedUser.id)")
} catch {
    print("Error: \(error)")
}

Third-Party Libraries

For advanced UUID versions, consider:

swift
// Using Swift Package Manager, add to Package.swift:
// .package(url: "https://github.com/vapor/uuid-kit.git", from: "1.0.0")

// Example with hypothetical UUID library
/*
import UUIDKit

let uuid1 = UUID.v1()
let uuid3 = UUID.v3(namespace: .url, name: "https://example.com")
let uuid5 = UUID.v5(namespace: .url, name: "https://example.com")
let uuid6 = UUID.v6()
let uuid7 = UUID.v7()
*/

UUID Version Comparison

Choose the right version for your Swift application:

  • Version 1 - Time-based, includes MAC address
  • Version 3 - MD5 namespace-based, deterministic
  • Version 4 - Random, most popular choice (built-in Swift support)
  • Version 5 - SHA-1 namespace-based, more secure than v3
  • Version 6 - Time-ordered, better than v1 for databases
  • Version 7 - Modern time-based with improved sorting

For Swift applications:

  • iOS apps: Use Version 4 for user sessions and local data
  • Core Data: Consider Version 7 for time-ordered entities
  • CloudKit sync: Use Version 1 for device-specific tracking

How do I generate UUID in other languages?

Mobile development:

  • Dart - Flutter cross-platform development
  • Kotlin - Android native development
  • Java - Android and enterprise applications

Backend services:

  • JavaScript - crypto.randomUUID() & uuid library
  • Python - Built-in uuid module
  • C# - System.Guid & UuidCreator
  • Go - google/uuid package

← Back to Online UUID Generator