The sad state of @AppStorage and the Observable framework
You thought you could use @AppStorage and the new @Observable? Think again!
As weird as it seems, the @AppStorage
new macro does not support the property wrapper. If, like me you had ObservableObject
with @AppStorage
properties in them, which were working precisely as @Published
properties, it simply won’t compile once you migrate your object to @Observable
.
But we have a solution, thanks to David Steppenbeck. He made a swift macro that allows a property to be backed by UserDefault and observed.
Update: David Steppenbeck also made a post on Medium about it!
You can add it as a Swift Package to your project.
And you use it like so
import ObservableUserDefault
@Observable
final class StorageModel {
@ObservableUserDefault(.init(key: "NAME_STORAGE_KEY", defaultValue: "John Appleseed", store: .standard))
@ObservationIgnored
var name: String
}
Unfortunately, in the case of Ice Cubes, I’ve made a lot of AppStorage use. I’ve made an extension to store Codable, and I keep a lot of enums also. I need to get familiar with Swift macros to add support to what I need in David’s macro.
So my UserPreferences
and Theme
environment object will stay ObservableObect
for now. It’s the only two remaining objects I need to migrate to the new observation framework.
I am confident that Apple will provide proper AppStorage support in an upcoming minor release of the iOS SDK. It’s a bit crazy, honestly, that it was not included in the 17.0 release.