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 crash when StoredState needs to be Data #89

Merged
merged 1 commit into from
Jan 26, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ extension Application {
}

/// `StoredState` encapsulates the value within the application's scope and allows any changes to be propagated throughout the scoped area. State is stored using `UserDefaults`.
public struct StoredState<Value>: MutableApplicationState {
public struct StoredState<Value: Codable>: MutableApplicationState {
@AppDependency(\.userDefaults) private var userDefaults: UserDefaults

/// The initial value of the state.
Expand All @@ -26,7 +26,17 @@ extension Application {
}

guard
let object = userDefaults.object(forKey: scope.key),
let object = userDefaults.object(forKey: scope.key)
else { return initial() }

if
let data = object as? Data,
let decodedValue = try? JSONDecoder().decode(Value.self, from: data)
{
return decodedValue
}

guard
let storedValue = object as? Value
else { return initial() }

Expand All @@ -48,7 +58,12 @@ extension Application {
),
forKey: scope.key
)
userDefaults.set(newValue, forKey: scope.key)

if let encodedValue = try? JSONEncoder().encode(newValue) {
userDefaults.set(encodedValue, forKey: scope.key)
} else {
userDefaults.set(newValue, forKey: scope.key)
}
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/AppState/PropertyWrappers/State/StoredState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import SwiftUI
#endif

/// `StoredState` is a property wrapper allowing SwiftUI views to subscribe to Application's state changes in a reactive way. State is stored using `UserDefaults`. Works similar to `State` and `Published`.
@propertyWrapper public struct StoredState<Value> {
@propertyWrapper public struct StoredState<Value: Codable> {
#if !os(Linux) && !os(Windows)
/// Holds the singleton instance of `Application`.
@ObservedObject private var app: Application = Application.shared
Expand Down
Loading