From 65b050308705c56d998371ec90a6ff793c148aa1 Mon Sep 17 00:00:00 2001 From: Brandon Williams Date: Tue, 12 Nov 2024 09:52:15 -0500 Subject: [PATCH] Fix exclusive access problem in preview traits. --- .../Dependencies/Traits/PreviewTrait.swift | 4 +++- .../PreviewTraitsTests.swift | 21 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 Tests/DependenciesTests/PreviewTraitsTests.swift 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..f78f02fd --- /dev/null +++ b/Tests/DependenciesTests/PreviewTraitsTests.swift @@ -0,0 +1,21 @@ +#if 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: 1234567890)) + withDependencies { + $0.context = .preview + } operation: { + @Dependency(\.date.now) var now + #expect(now == Date(timeIntervalSince1970: 1234567890)) + } + } +} +#endif