withDependencies(isolation:_:operation:)

Updates the current dependencies for the duration of an asynchronous operation.

WithDependencies.swift:80
@discardableResult func withDependencies<R>(isolation: isolated (any Actor)? = #isolation, _ updateValuesForOperation: (inout DependencyValues) async throws -> Void, operation: () async throws -> R) async rethrows -> R

Parameters

updateValuesForOperation

A closure for updating the current dependency values for the duration of the operation.

operation

An operation to perform wherein dependencies have been overridden.

Returns

The result returned from operation.

Any mutations made to DependencyValues inside updateValuesForOperation will be visible to everything executed in the operation. For example, if you wanted to force the date dependency to be a particular date, you can do:

await withDependencies {
  $0.date.now = Date(timeIntervalSince1970: 1234567890)
} operation: {
  // References to date in here are pinned to 1234567890.
}