UUID Generator — Swift source
Generate RFC 4122 v4 UUIDs with crypto-grade randomness. Bulk generate, copy all, toggle format (uppercase / no hyphens).
This is the Swift implementation — the same logic the interactive tool runs, in a shareable, citable form.
// RFC 4122 v4 UUID generator (cryptographically secure).
//
// Language: Swift (5.x, Foundation + Security)
// CosmoDev polyglot showcase port of the `uuid` tool.
// Ported from src/lib/uuid.ts — display source, part of CosmoDev's
// polyglot tool pages.
//
// Produces a random (v4) UUID: 36 characters, lowercase, hyphenated as
// 8-4-4-4-12 hex digits, with the RFC version (4) and variant (10xx)
// bits set. SecRandomCopyBytes is Apple's bridge to the host CSPRNG;
// a non-zero status is the explicit "entropy source unavailable"
// error path.
import Foundation
import Security
/// Return a freshly generated RFC 4122 version-4 UUID string.
func uuidV4() -> String {
var b = [UInt8](repeating: 0, count: 16)
let status = SecRandomCopyBytes(kSecRandomDefault, b.count, &b)
precondition(status == errSecSuccess, "entropy source unavailable")
b[6] = (b[6] & 0x0f) | 0x40 // version 4: high nibble of byte 6
b[8] = (b[8] & 0x3f) | 0x80 // variant : high bits of byte 8
// Lowercase hex, hyphens at the 8-4-4-4-12 boundaries.
let hexed = b.map { String(format: "%02x", $0) }.joined()
return [
hexed.prefix(8),
hexed.dropFirst(8).prefix(4),
hexed.dropFirst(12).prefix(4),
hexed.dropFirst(16).prefix(4),
hexed.dropFirst(20),
].joined(separator: "-")
}
print(uuidV4())
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →