In my app i have several scenarios, each showing a different UIAlertController
, so i created a function to show this alert, but i can't seem to call self.Function inside the "okAction" . I'm getting this error :
Value of type
'ViewController'
has no member'doAction'
Here's the code :
func showAlertController( titleOfAlert: String, messageOfAlert : String, doAction : () )
{
let refreshAlert = UIAlertController(title: titleOfAlert, message: messageOfAlert, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "Save", style: UIAlertActionStyle.Default) {
UIAlertAction in
self.doAction()
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default) {
UIAlertAction in
}
refreshAlert.addAction(okAction)
refreshAlert.addAction(cancelAction)
self.presentViewController(refreshAlert, animated: true, completion: nil)
}
Here's one of the functions that i'm calling :
func changeLabel1()
{
label.text = "FOR BUTTON 1"
}
How can i solve it ?
remove the self
in front of doAction()
since you do not call the action on the object self.
If you do that the compiler will tell youInvalid use of '()' to call a value of non-function type '()'
. That is the case because doAction
is no function but an empty tuple. A function has input parameters and a return type. Therefore the type of doAction
should be () -> Void
- it takes no input and returns Void
, i.e. does not return anything.
The code should be like this:
func showAlertController( titleOfAlert: String, messageOfAlert : String, doAction : () -> Void ) {
...
let okAction = UIAlertAction(title: "Save", style: UIAlertActionStyle.Default) { action in
doAction()
}
...
}
If you want to pass the action
to the doAction
method you would have to change the type to (UIAlertAction) -> Void
and call it via doAction(action)
.
From your code doAction is the third parameter of function showAlertController.
so First: change doAction : () to doAction: ()->() It means that doAction is a Closure without parameters and empty return.
Second: the call shouldn't be self.doAction() but just doAction() Because its a parameter and not an instance variable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With