From 9de16b3e964394a3ee32dff2bbb3e340a1e2173a Mon Sep 17 00:00:00 2001 From: Brandon Williams <135203+mbrandonw@users.noreply.github.com> Date: Tue, 30 Apr 2024 11:03:50 -0700 Subject: [PATCH] Fix @Shared initializer with default nil. (#3035) * Fix @Shared initializer with default nil. * wip --- .../SharedState/PersistenceKey/AppStorageKey.swift | 13 ++++++++----- .../AppStorageTests.swift | 7 +++++++ 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/Sources/ComposableArchitecture/SharedState/PersistenceKey/AppStorageKey.swift b/Sources/ComposableArchitecture/SharedState/PersistenceKey/AppStorageKey.swift index 498a67793110..52e59ea1947f 100644 --- a/Sources/ComposableArchitecture/SharedState/PersistenceKey/AppStorageKey.swift +++ b/Sources/ComposableArchitecture/SharedState/PersistenceKey/AppStorageKey.swift @@ -282,9 +282,7 @@ extension AppStorageKey: PersistenceKey { } public func save(_ value: Value) { - SharedAppStorageLocals.$isSetting.withValue(true) { - self.lookup.saveValue(value, to: self.store, at: self.key) - } + self.lookup.saveValue(value, to: self.store, at: self.key) } public func subscribe( @@ -373,13 +371,18 @@ private struct CastableLookup: Lookup { ) -> Value? { guard let value = store.object(forKey: key) as? Value else { - store.setValue(defaultValue, forKey: key) + SharedAppStorageLocals.$isSetting.withValue(true) { + store.setValue(defaultValue, forKey: key) + } return defaultValue } return value } + func saveValue(_ newValue: Value, to store: UserDefaults, at key: String) { - store.setValue(newValue, forKey: key) + SharedAppStorageLocals.$isSetting.withValue(true) { + store.setValue(newValue, forKey: key) + } } } diff --git a/Tests/ComposableArchitectureTests/AppStorageTests.swift b/Tests/ComposableArchitectureTests/AppStorageTests.swift index 039bcdb19735..dbe5a1417c42 100644 --- a/Tests/ComposableArchitectureTests/AppStorageTests.swift +++ b/Tests/ComposableArchitectureTests/AppStorageTests.swift @@ -142,6 +142,13 @@ final class AppStorageTests: XCTestCase { defaults.count += 1 XCTAssertEqual(count, 1) } + + func testOptionalInitializers() { + @Shared(.appStorage("count1")) var count1: Int? + XCTAssertEqual(count1, nil) + @Shared(.appStorage("count")) var count2: Int? = nil + XCTAssertEqual(count2, nil) + } } extension UserDefaults {