uuid

A dependency that generates UUIDs.

UUID.swift:64DependencyValuesUUID.md
var uuid: UUIDGenerator { get set }

Introduce controllable UUID generation to your features by using the Dependency property wrapper with a key path to this property. The wrapped value is an instance of UUIDGenerator, which can be called with a closure to create UUIDs. (It can be called directly because it defines callAsFunction, which is called when you invoke the instance as you would invoke a function.)

For example, you could introduce controllable UUID generation to an observable object model that creates to-dos with unique identifiers:

@Observable
final class TodosModel {
  var todos: [Todo] = []

  @ObservationIgnored
  @Dependency(\.uuid) var uuid

  func addButtonTapped() {
    todos.append(Todo(id: uuid()))
  }
}

By default, a “live” generator is supplied, which returns a random UUID when called by invoking UUID.init under the hood. When used in tests, an “unimplemented” generator that additionally reports test failures if invoked, unless explicitly overridden.

To test a feature that depends on UUID generation, you can override its generator using withDependencies(_:operation:) to override the underlying UUIDGenerator:

  • incrementing for reproducible UUIDs that count up from 00000000-0000-0000-0000-000000000000.

  • constant(_:) for a generator that always returns the given UUID.

For example, you could test the to-do-creating model by supplying an incrementing generator as a dependency:

@Test
func feature() {
  let model = withDependencies {
    $0.uuid = .incrementing
  } operation: {
    TodosModel()
  }

  model.addButtonTapped()
  #expect(
    model.todos == [
      Todo(id: UUID(0))
    ]
  )
}

Dependency value