Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions Sources/Dependencies/Dependency.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,19 @@
/// entry" concept. See the articles <doc:Lifetimes> and <doc:SingleEntryPointSystems> for more
/// information.
///
/// > Important: Do **not** use `@Dependency` with "static" properties, _e.g._:
/// >
/// > ```swift
/// > struct User {
/// > @Dependency(\.uuid) static var uuid
/// > // ...
/// > }
/// > ```
/// >
/// > Static properties are lazily initialized in Swift, and so a static `@Dependency` will lazily
/// > capture its dependency values wherever it is first accessed, and will likely produce
/// > unexpected behavior.
///
/// For the complete list of dependency values provided by the library, see the properties of the
/// ``DependencyValues`` structure.
///
Expand Down
23 changes: 23 additions & 0 deletions Tests/DependenciesTests/DependencyTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,30 @@ final class DependencyTests: XCTestCase {
XCTAssertEqual(9000, greatGrandchild.int)
XCTAssertEqual("cool", greatGrandchild.string)
}

// NB: `@Dependency` should not be used as a `static var` because of the following behavior.
func testStaticDependencyCachesFirstUse() {
struct User {
@Dependency(\.uuid) static var uuid

let id: UUID

init() {
self.id = Self.uuid()
}
}

let user1 = withDependencies { $0.uuid = .incrementing } operation: {
User()
}

let user2 = User()

XCTAssertEqual(user1.id, UUID(0))
XCTAssertEqual(user2.id, UUID(1))
}
}

private class Model {
@Dependency(\.int) var int
@Dependency(\.string) var string
Expand Down