sindresorhus / Defaults

💾 Swifty and modern UserDefaults
https://swiftpackageindex.com/sindresorhus/Defaults/documentation/defaults
MIT License
1.93k stars 115 forks source link

Support using `@Default` in `@Observable` classes #142

Open sindresorhus opened 1 year ago

sindresorhus commented 1 year ago

I think we can finally support @Default in observable classes.

More info: https://github.com/apple/swift-evolution/blob/main/proposals/0395-observability.md

@Obserable expands class properties to:

var order: Order? {
    get { 
        self.access(keyPath: \.order)
        return _order
    }
    set {
        self.withMutation(keyPath: \.order) {
            _order = newValue
        }
    }
}

So we could make a macro that could be attached a property and it would generate similar code, but also integrate with Defaults.

It would be nice if @Default could be reused, but I'm not sure whether it's possible.

I'm open to other ideas on how to make us able to integrate Defaults into @Observable classes.

There is no rush with this one. We will probably not do anything about it until after iOS 17 is out.

After iOS 17 is out, we could also maybe try to expand @AppStorage and see if it's a macro then, and if so, what it generates.

staticdreams commented 10 months ago

Any updates on this? iOS17 is just around the corner and I'm in the process of migrating @ObservableObject to Observable

sindresorhus commented 10 months ago

This will unfortunately not happen soon unless someone contributes the functionality. Creating a macro is not easy, and the macro system is still in flux. Even the built-in @AppStorage does not yet work with @Observable.

For now, you could use either of these packages. They work with Defaults if you use the same key.