Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why isn't my generated function being executed?

I have a logout button as follows:

struct LogoutButtonView: View {
    @EnvironmentObject var state: AppState
    @StateObject var viewModel = ViewModel()
    
    var body: some View {
        Button("Log Out") { viewModel.isConfirming = true }
        .confirmationDialog("Are you that you want to logout",
                            isPresented: $viewModel.isConfirming) {
            Button("Confirm Logout", role: .destructive, action: viewModel.getLogoutAction(state: state))
            Button("Cancel", role: .cancel) {}
        }
        .disabled(state.shouldIndicateActivity)
    }
}

Its view model is as follows:

extension LogoutButtonView {
    class ViewModel: ObservableObject {
        @Published var isConfirming = false
        
        func getLogoutAction(state: AppState) -> () -> Void {
            print("Inside getLogoutAction")
            return {
                func logout() {
                    print("Inside Logout")
                    state.shouldIndicateActivity = true
                    // .. Logout Logic
                }
            }
        }
    }
}

I need to pass down the reference of global AppState to the view model, that’s why I am trying to generate the logout function instead of directly putting that in my view model.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Why is it not printing "Inside Logout"? How does Swift work in terms of Functional Programming? What’s the correct approach to update/access global AppState from the local view model?

>Solution :

The answer is that you never call logout().

It’s true that you return the function on a button tap, but you don’t call the returned (logout) function. So it’s never executed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading