Skip to content

Instantly share code, notes, and snippets.

@SergLam
Forked from xsleonard/UUID+Extensions.swift
Last active March 28, 2025 11:26
Show Gist options
  • Save SergLam/95bc7428c0a63f2bb39cb17d8b71bff3 to your computer and use it in GitHub Desktop.
Save SergLam/95bc7428c0a63f2bb39cb17d8b71bff3 to your computer and use it in GitHub Desktop.
Swift: Convert UUID to and from Data and Int64
import Foundation
extension UUID {
// UUID is 128-bit, we need two 64-bit values to represent it
var integers: (Int64, Int64) {
var first: UInt64 = 0
first |= UInt64(uuid.0)
first |= UInt64(uuid.1) << 8
first |= UInt64(uuid.2) << (8 * 2)
first |= UInt64(uuid.3) << (8 * 3)
first |= UInt64(uuid.4) << (8 * 4)
first |= UInt64(uuid.5) << (8 * 5)
first |= UInt64(uuid.6) << (8 * 6)
first |= UInt64(uuid.7) << (8 * 7)
var second: UInt64 = 0
second |= UInt64(uuid.8)
second |= UInt64(uuid.9) << 8
second |= UInt64(uuid.10) << (8 * 2)
second |= UInt64(uuid.11) << (8 * 3)
second |= UInt64(uuid.12) << (8 * 4)
second |= UInt64(uuid.13) << (8 * 5)
second |= UInt64(uuid.14) << (8 * 6)
second |= UInt64(uuid.15) << (8 * 7)
return (Int64(bitPattern: first), Int64(bitPattern: second))
}
static func from(integers: (Int64, Int64)) -> UUID {
let first = UInt64(bitPattern: integers.0)
let second = UInt64(bitPattern: integers.1)
return UUID(uuid: (
UInt8(first & 0xFF),
UInt8((first >> 8) & 0xFF),
UInt8((first >> (8 * 2)) & 0xFF),
UInt8((first >> (8 * 3)) & 0xFF),
UInt8((first >> (8 * 4)) & 0xFF),
UInt8((first >> (8 * 5)) & 0xFF),
UInt8((first >> (8 * 6)) & 0xFF),
UInt8((first >> (8 * 7)) & 0xFF),
UInt8(second & 0xFF),
UInt8((second >> 8) & 0xFF),
UInt8((second >> (8 * 2)) & 0xFF),
UInt8((second >> (8 * 3)) & 0xFF),
UInt8((second >> (8 * 4)) & 0xFF),
UInt8((second >> (8 * 5)) & 0xFF),
UInt8((second >> (8 * 6)) & 0xFF),
UInt8((second >> (8 * 7)) & 0xFF)
))
}
var data: Data {
var data = Data(count: 16)
// uuid is a tuple type which doesn't
// have dynamic subscript access...
data[0] = uuid.0
data[1] = uuid.1
data[2] = uuid.2
data[3] = uuid.3
data[4] = uuid.4
data[5] = uuid.5
data[6] = uuid.6
data[7] = uuid.7
data[8] = uuid.8
data[9] = uuid.9
data[10] = uuid.10
data[11] = uuid.11
data[12] = uuid.12
data[13] = uuid.13
data[14] = uuid.14
data[15] = uuid.15
return data
}
static func from(data: Data?) -> UUID? {
guard data?.count == MemoryLayout<uuid_t>.size else {
return nil
}
return data?.withUnsafeBytes {
guard let baseAddress = $0.bindMemory(to: UInt8.self).baseAddress else {
return nil
}
return NSUUID(uuidBytes: baseAddress) as UUID
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment