ObservablePersistency is a SwiftUI library that adds persistency support to @Observable, which unlike ObservableObject can't use @AppStorage and SceneStorage property wrappers.
By implementing the ObservablePersisted protocol, an @Observable class gets access to key(_:default:), getValue(for:store:) and setValue(_:for:store:) functions:
@Observable
public class AdminContext: ObservablePersisted {
private static let adminKey = key("isAdminModeEnabled", default: false)
/// Whether or not admin mode is enabled.
public var isAdminModeEnabled = getValue(for: adminKey) {
didSet { setValue(isAdminModeEnabled, for: Self.adminKey) }
}
}This makes it a little cleaner to make a property auto-persisted, compared to explicitly reading from and writing to UserDefaults.
ObservablePersistency can be installed with the Swift Package Manager:
https://github.com/danielsaidi/ObservablePersistency.git
You can become a sponsor to help me dedicate more time on my various open-source tools. Every contribution, no matter the size, makes a real difference in keeping these tools free and actively developed.
Feel free to reach out if you have questions or want to contribute in any way:
- Website: danielsaidi.com
- E-mail: daniel.saidi@gmail.com
- Bluesky: @danielsaidi@bsky.social
- Mastodon: @danielsaidi@mastodon.social
ObservablePersistency is available under the MIT license. See the LICENSE file for more info.