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.
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?
CodePudding user response:
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.