I'm trying to get more into the Swift Closure concept and I have this problem, I have the following UIAlertController method:
public static func showSerialNumberAlertController(handler: @escaping (UIAlertAction) -> String?) {
let alertController = UIAlertController(title: "Serial Number", message: "Please enter your serial number", preferredStyle: .alert)
// ADD ACTIONS HANDLER
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
cancelAction.isEnabled = true
alertController.addAction(cancelAction)
let continueAction = UIAlertAction(title: "Continue", style: .default) { (_) in
let serialNumberField = alertController.textFields![0] as UITextField
let text = serialNumberField.text
print("Serial number entered: \(text!)")
}
continueAction.isEnabled = false
alertController.addAction(continueAction)
// ADD TEXT FIELDS
alertController.addTextField { (textField) in
textField.placeholder = "Serial number"
// enable continue button when serial not empty
NotificationCenter.default.addObserver(forName: NSNotification.Name.UITextFieldTextDidChange, object: textField, queue: OperationQueue.main) { (notification) in
continueAction.isEnabled = textField.text != "" && textField.text?.count as! Int > 3
}
}
alertController.view.tintColor = Colors.mainColor
getRootViewController()?.present(alertController, animated: true)
}
now what I'm trying to do is to replace the handler of the continueAction
UIAlertAction
with a handler I receive from outside which will extract the text from the serial number UITextField
when the user presses the continue button and pass it as the returned value.
So I have this method outside of this scope in another file, from which I'm calling this static method:
public func getSerialFromAlert(alertController: UIAlertController) -> String?
{
let serialNumberField = alertController.textFields![0] as UITextField
let text = serialNumberField.text
print("Serial number entered: \(text!)")
return text
}
I want to pass this method as a handler but when I do that I get this error:
Cannot convert value of type '(UIAlertAction) -> String?' to expected argument type '((UIAlertAction) -> Void)?'
So the question is: Is it possible to achieve this and pass a handler that will return a value as a parameter? If so what would be the right way to do this? If not, what would be the alternative for an UIAlertController
action delegate that has to access alert views in order to extract data?