UUID - zero value

Hi,

Overview

  • I am using UUID to generate unique values for an id field.
  • However I have a scenario in which I need to check if it matches a special value to do something special.
  • I can't have the id field as an optional, the real use case is in AppIntents.

Question

  1. What is the way to define a special UUID that I can be sure UUID() will not generate?
  2. Can I use UUID(uuid: (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))?
  3. Or is there a better way to handle such a scenario?

Code:

struct Car {
    let id: UUID
    let name: String
    
    static let demo = Car(id: .zero, name: "Demo Car")
}

extension UUID {
    static let zero = UUID(uuid: (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
}

let c1 = Car(id: UUID(), name: "Car 1")
let c2 = Car(id: UUID(), name: "Car 2")

let demoCar = Car.demo

print(c1)
print(c2)
print(demoCar)

That should be find. Check out the discussion of nil and max UUIDs in RFC 9562

Oh, and there’s a fascinating discussion about this stuff currently going on over in Related Products > Foundation.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

3 Likes

Thank you so much @eskimo Quinn!!

Really happy about the proposal @Tony_Parker, the sentinel values would be great!! Thanks!!

UUID(uuid: UUID_NULL) also works, when using Apple platforms.

2 Likes

Thanks a lot @x-sheep for that tip!

You can also take the init from swift-dependencies, which allows you to call it like UUID(0). Library is a pretty good dependency solution too.