I was extracting closure to method but I always get this error:
Function is unused
This is whole working func:
fileprivate func attemptToChangePassword() {
passwordChanger.change(securityToken: securityToken, oldPassword: oldPassword.text ?? "", newPassword: newPassword.text ?? "", onSuccess:{[weak self] in
self?.hideSpinner()
let alertController = UIAlertController(
title: nil,
message: "Your password has been successfully changed.",
preferredStyle: .alert)
let okButton = UIAlertAction(
title: "OK",
style: .default) { [weak self] _ in
self?.dismiss(animated: true)
}
alertController.addAction(okButton)
alertController.preferredAction = okButton
self?.present(alertController, animated: true)
}, onFailure: {[weak self] message in
self?.hideSpinner()
self?.showAlert(message: message) { [weak self] _ in
self?.oldPassword.text = ""
self?.newPassword.text = ""
self?.confirmPassword.text = ""
self?.oldPassword.becomeFirstResponder()
self?.view.backgroundColor = .white
self?.blurView.removeFromSuperview()
self?.cancel.isEnabled = true
}
})
}
This is how I extracted last closure to method:
fileprivate func startOver() -> (UIAlertAction) -> Void {
return { [weak self] _ in
self?.oldPassword.text = ""
self?.newPassword.text = ""
self?.confirmPassword.text = ""
self?.oldPassword.becomeFirstResponder()
self?.view.backgroundColor = .white
self?.blurView.removeFromSuperview()
self?.cancel.isEnabled = true
}
}
If I try this, the error "Function is unused" shows up:
onFailure: { [weak self] message in
self?.hideSpinner()
self?.showAlert(message: message) { [weak self] _ in
self?.startOver()//FUNCTION IS UNUSED
}
})
Edit:
Here is alert method that is used:
fileprivate func showAlert( message: String, okAction: @escaping (UIAlertAction) -> Void) {
let ac = UIAlertController(title: nil, message: message, preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler:okAction)
ac.addAction(ok)
ac.preferredAction = ok
self.present(ac, animated: true)
}
If I add back alert action button it works:
let okButton = UIAlertAction(
title: "OK",
style: .default,
handler:startOver())
CodePudding user response:
You're currently calling that function inside of the action you pass to your showAlert
function but then throwing away the action it returns. Instead, you want to pass the action that it returns directly to your showAlert
method rather than wrapping it inside another action with the trailing closure syntax:
self?.showAlert(message: message, okAction: self!.startOver())