Back to Blog

Swift: UUID to odd or even number

Sandy LaneSandy Lane

Video: Swift: UUID to odd or even number by Taught by Celeste AI - AI Coding Coach

Watch full page →

Swift: UUID to Odd or Even Number

In Swift, you can determine whether a UUID corresponds to an odd or even number by examining part of its data. Since UUIDs are 128-bit values, a simple approach is to convert a portion of the UUID to an integer and check its parity. This technique is useful when you want to assign entities randomly but consistently to odd or even groups based on their UUID.

Code

import Foundation

// Generate a new UUID
let uuid = UUID()
print("UUID: \(uuid)")

// Extract the UUID string without hyphens
let uuidString = uuid.uuidString.replacingOccurrences(of: "-", with: "")

// Convert the last character of the UUID string to an integer (hex digit)
if let lastHexChar = uuidString.last,
   let lastDigit = Int(String(lastHexChar), radix: 16) {
  // Check if the digit is odd or even
  if lastDigit % 2 == 0 {
    print("The UUID corresponds to an even number.")
  } else {
    print("The UUID corresponds to an odd number.")
  }
} else {
  print("Failed to parse the UUID.")
}

Key Points

  • A UUID can be interpreted as a hexadecimal string, allowing numeric operations on parts of it.
  • Extracting the last hex digit and converting it to an integer is a simple way to check odd/even parity.
  • Using modulo (%) on the integer determines whether the number is odd or even.
  • This method provides a deterministic way to categorize UUIDs without complex hashing.