Skip to content

Commit

Permalink
Fix @shared initializer with default nil. (#3035)
Browse files Browse the repository at this point in the history
* Fix @shared initializer with default nil.

* wip
  • Loading branch information
mbrandonw committed Apr 30, 2024
1 parent 57cfcb6 commit 9de16b3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -373,13 +371,18 @@ private struct CastableLookup<Value>: 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)
}
}
}

Expand Down
7 changes: 7 additions & 0 deletions Tests/ComposableArchitectureTests/AppStorageTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 9de16b3

Please sign in to comment.