Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Published for a computed property (or best workaround)

I'm trying to build an app with SwiftUI, and I'm just getting started with Combine framework. My first simple problem is that I'd like a single variable that defines when the app has been properly initialized. I'd like it to be driven by some nested objects, though. For example, the app is initialized when the account object is initialized, the project object is initialized, etc. My app could then use GlobalAppState.isInitialized, instead of inspected each nested object.

class GlobalAppState: ObservableObject {

    @Published var account: Account = Account()
    @Published var project: Project = Project()

    @Published var isInitialized: Bool {
        return self.account.initialized && self.project.initialized;
    }
}

I get the error Property wrapper cannot be applied to a computed property

So...clearly, this is currently disallowed. Is there a way I can work around this??? I'd like to be able to use GlobalAppState.initialized as a flag in the app. More to the point, something like GlobalAppState.project.currentProject, which would be a computed property returning the currently selected project, etc...

I can see this pattern being used in a thousand different places! Any help would be wildly appreciated...

Thanks!

like image 434
Hoopes Avatar asked Dec 13 '22 09:12

Hoopes


1 Answers

In this case there's no reason to use @Published for the isInialized property since it's derived from two other Published properties.

    var isInitialized: Bool {
        return self.account.initialized && self.project.initialized;
    }
like image 92
Gil Birman Avatar answered Jan 12 '23 10:01

Gil Birman