somu
(somu)
1
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
- What is the way to define a special UUID that I can be sure
UUID() will not generate?
- Can I use
UUID(uuid: (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))?
- 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)
eskimo
(Quinn “The Eskimo!”)
2
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
somu
(somu)
3
Thank you so much @eskimo Quinn!!
Really happy about the proposal @Tony_Parker, the sentinel values would be great!! Thanks!!
x-sheep
(Lennard Sprong)
4
UUID(uuid: UUID_NULL) also works, when using Apple platforms.
2 Likes
somu
(somu)
5
Thanks a lot @x-sheep for that tip!
Jon_Shier
(Jon Shier)
6
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.