Skip to content

Commit

Permalink
Don’t assume CastableLookup (#3011)
Browse files Browse the repository at this point in the history
* Don’t assume CastableLookup

If the observed value in `UserDefaults` is a `RawRepresentable` type, simply casting to `Value` might fail because the raw representing type could be different from `Value`.  Instead of querying `UserDefaults` directly here, we should call `loadValue()` which will do the right thing for raw representable types (esp. try to call `Value.init(rawValue:)` with the value obtained from `UserDefaults`).

* Add test

---------

Co-authored-by: Stephen Celis <stephen@stephencelis.com>
  • Loading branch information
AlexKobachiJP and stephencelis authored Apr 26, 2024
1 parent a2442ee commit 03d4037
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ extension AppStorageKey: PersistenceKey {
) { _ in
guard !SharedAppStorageLocals.isSetting
else { return }
didSet(self.store.value(forKey: self.key) as? Value ?? initialValue)
didSet(load(initialValue: initialValue))
}
let willEnterForeground: (any NSObjectProtocol)?
if let willEnterForegroundNotificationName {
Expand All @@ -307,7 +307,7 @@ extension AppStorageKey: PersistenceKey {
object: nil,
queue: nil
) { _ in
didSet(self.store.value(forKey: self.key) as? Value ?? initialValue)
didSet(load(initialValue: initialValue))
}
} else {
willEnterForeground = nil
Expand Down
10 changes: 10 additions & 0 deletions Tests/ComposableArchitectureTests/AppStorageTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,16 @@ final class AppStorageTests: XCTestCase {
XCTAssertEqual(count, 42)
}

func testChangeUserDefaultsDirectly_RawRepresentable() {
enum Direction: String, CaseIterable {
case north, south, east, west
}
@Dependency(\.defaultAppStorage) var defaults
@Shared(.appStorage("direction")) var direction: Direction = .south
defaults.set("east", forKey: "direction")
XCTAssertEqual(direction, .east)
}

func testChangeUserDefaultsDirectly_KeyWithPeriod() {
@Dependency(\.defaultAppStorage) var defaults
@Shared(.appStorage("pointfreeco.count")) var count = 0
Expand Down

0 comments on commit 03d4037

Please sign in to comment.