Skip to content

Commit

Permalink
Allow and prefer Optional values for StoredState
Browse files Browse the repository at this point in the history
  • Loading branch information
0xLeif committed Nov 5, 2023
1 parent 2eeab55 commit f40b158
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 19 deletions.
23 changes: 15 additions & 8 deletions Sources/AppState/Application+StoredState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,22 @@ extension Application {
}
set {
let userDefaults = Application.dependency(\.userDefaults)
let mirror = Mirror(reflecting: newValue)

shared.cache.set(
value: Application.State(
initial: newValue,
scope: scope
),
forKey: scope.key
)
userDefaults.set(newValue, forKey: scope.key)
if mirror.displayStyle == .optional,
mirror.children.isEmpty {
shared.cache.remove(scope.key)
userDefaults.removeObject(forKey: scope.key)
} else {
shared.cache.set(
value: Application.State(
initial: newValue,
scope: scope
),
forKey: scope.key
)
userDefaults.set(newValue, forKey: scope.key)
}
}
}

Expand Down
22 changes: 11 additions & 11 deletions Tests/AppStateTests/AppStateTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ extension Application {
state(initial: ["primary": CGColor(red: 1, green: 0, blue: 1, alpha: 1)])
}

var storedValue: StoredState<Int> {
storedState(initial: -1, id: "storedValue")
var storedValue: StoredState<Int?> {
storedState(initial: nil, id: "storedValue")
}
}

Expand Down Expand Up @@ -141,34 +141,34 @@ final class AppStateTests: XCTestCase {
}

func testStoredState() {
XCTAssertEqual(Application.storedState(\.storedValue).value, -1)
XCTAssertNil(Application.storedState(\.storedValue).value)

let storedValue = ExampleStoredValue()

XCTAssertEqual(storedValue.count, -1)
XCTAssertEqual(storedValue.count, nil)

storedValue.count = 2
storedValue.count = 1

XCTAssertEqual(storedValue.count, 2)
XCTAssertEqual(storedValue.count, 1)

Application.remove(storedState: \.storedValue)
storedValue.count = nil

XCTAssertEqual(Application.storedState(\.storedValue).value, -1)
XCTAssertNil(Application.storedState(\.storedValue).value)
}

func testStoringViewModel() {
XCTAssertEqual(Application.storedState(\.storedValue).value, -1)
XCTAssertNil(Application.storedState(\.storedValue).value)

let viewModel = ExampleStoringViewModel()

XCTAssertEqual(viewModel.count, -1)
XCTAssertEqual(viewModel.count, nil)

viewModel.count = 2

XCTAssertEqual(viewModel.count, 2)

Application.remove(storedState: \.storedValue)

XCTAssertEqual(viewModel.count, -1)
XCTAssertNil(viewModel.count)
}
}

0 comments on commit f40b158

Please sign in to comment.