@Observable and @AppStorage

Converting

class Model: ObservableObject {
    @AppStorage("prop0") var prop0 = 0
}

to

@Observable struct Model {
    @AppStorage("prop0") var prop0 = 0
}

created error: Property wrapper cannot be applied to a computed property

How can properties of @Observable models be saved in user defaults?

I watched several SwiftUI sessions (e.g., https://developer.apple.com/videos/play/wwdc2023/10148/?time=621) they all apply @Observable to clas, not struct.

Dis you try

@Observable class Model {
    @AppStorage("prop0") var prop0 = 0
}

And there is the new SwiftData (same session) to save persistent data.

AppStorage doesn't work in Observable objects, don't if this is a beta bug tho.

@Observable should only be used on reference types, or to be more precise classes.

With @Observable or SwiftData model, how to share data between iOS app and widgets, if @AppStorage is unavailable?

The error is due to the macro for @Observable converting prop0 to be a computed property. One alternative is this:

@Observable
final class Model {
    var prop0: Int {
        didSet {
            guard oldValue != self.prop0 else { return }
            UserDefaults.standard.set(self.prop0, forKey: "prop0")
        }
    }

    private init() {
        prop0 = UserDefaults.standard.integer(forKey: "prop0")
    }
}

Observation is not supported with AppStorage yet, but the solution is easy.

@Observable 
class CalculateViewModel {
    
    @ObservationIgnored @AppStorage("calculateCount") var calculateCount = 0
}
@Observable and @AppStorage
 
 
Q