DependencyValues

A collection of dependencies that is globally available.

DependencyValues.swift:119DependencyValues.md
struct DependencyValues

To access a particular dependency from the collection you use the Dependency property wrapper:

@Dependency(\.date) var date
// ...
let now = date.now

To change a dependency for a well-defined scope you can use the withDependencies(_:operation:) method:

@Dependency(\.date) var date
let now = date.now

withDependencies {
  $0.date.now = Date(timeIntervalSinceReferenceDate: 1234567890)
} operation: {
  @Dependency(\.date.now) var now: Date
  now.timeIntervalSinceReferenceDate  // 1234567890
}

The dependencies will be changed for the lifetime of the operation scope, which can be synchronous or asynchronous.

To register a dependency inside DependencyValues, you first create a type to conform to the DependencyKey protocol in order to specify the liveValue to use for the dependency when run in simulators and on devices. It can even be private:

private enum MyValueKey: DependencyKey {
  static let liveValue = 42
}

And then extend DependencyValues with a computed property that uses the key to read and write to DependencyValues:

extension DependencyValues {
  var myValue: Int {
    get { self[MyValueKey.self] }
    set { self[MyValueKey.self] = newValue }
  }
}

With those steps done you can access the dependency using the Dependency property wrapper:

@Dependency(\.myValue) var myValue
myValue  // 42

Read the article Registering dependencies for more information.

Creating and accessing values

  • init

  • ``subscript(key:file:function:line:)

Overriding values

Escaping contexts

Dependency values

Default contexts

Deprecations