diff --git a/Sources/Dependencies/Traits/PreviewTrait.swift b/Sources/Dependencies/Traits/PreviewTrait.swift index ff137ce0..adbe823c 100644 --- a/Sources/Dependencies/Traits/PreviewTrait.swift +++ b/Sources/Dependencies/Traits/PreviewTrait.swift @@ -47,7 +47,9 @@ public static func dependencies( _ updateValuesForPreview: (inout DependencyValues) -> Void ) -> PreviewTrait { - updateValuesForPreview(&previewValues) + var copy = previewValues + defer { previewValues = copy } + updateValuesForPreview(©) return PreviewTrait() } } diff --git a/Tests/DependenciesTests/PreviewTraitsTests.swift b/Tests/DependenciesTests/PreviewTraitsTests.swift new file mode 100644 index 00000000..3e9692a0 --- /dev/null +++ b/Tests/DependenciesTests/PreviewTraitsTests.swift @@ -0,0 +1,21 @@ +#if canImport(Testing) && (os(iOS) || os(macOS) || os(tvOS) || os(watchOS)) + import Dependencies + import Testing + import SwiftUI + + @Suite + @MainActor + struct PreviewTraitsTests { + @Test + @available(iOS 18, macOS 15, tvOS 18, watchOS 11, visionOS 2, *) + func dependency() { + _ = PreviewTrait.dependency(\.date.now, Date(timeIntervalSince1970: 1_234_567_890)) + withDependencies { + $0.context = .preview + } operation: { + @Dependency(\.date.now) var now + #expect(now == Date(timeIntervalSince1970: 1_234_567_890)) + } + } + } +#endif