Skip to content

Instantly share code, notes, and snippets.

@koher
Created February 14, 2023 13:14
Show Gist options
  • Save koher/b39e176110483e3821820fc8ca34000b to your computer and use it in GitHub Desktop.
Save koher/b39e176110483e3821820fc8ca34000b to your computer and use it in GitHub Desktop.
import Foundation
actor UUIDSerialNumberGenerator {
static let shared: UUIDSerialNumberGenerator = .init()
private var nextSerialNumber: Int = 0
private var uuidToSerialNumber: [UUID: Int] = [:]
private init() {}
func serialNumber(for uuid: UUID) -> Int {
if let serialNumber = uuidToSerialNumber[uuid] {
return serialNumber
}
uuidToSerialNumber[uuid] = nextSerialNumber
defer { nextSerialNumber += 1 }
return nextSerialNumber
}
}
let generator: UUIDSerialNumberGenerator = .shared
let a: UUID = .init()
let b: UUID = .init()
let c: UUID = .init()
let d: UUID = .init()
print(await generator.serialNumber(for: a))
print(await generator.serialNumber(for: b))
print(await generator.serialNumber(for: c))
print(await generator.serialNumber(for: d))
print(await generator.serialNumber(for: a))
print(await generator.serialNumber(for: b))
print(await generator.serialNumber(for: c))
print(await generator.serialNumber(for: d))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment