Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix @Shared initializer with default nil. #3035

Merged
merged 2 commits into from
Apr 30, 2024
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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