简体   繁体   中英

Swift - Value of Type ViewController has no member *functionName*

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 ?

  1. remove the self in front of doAction() since you do not call the action on the object self.

  2. If you do that the compiler will tell you
    Invalid 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 , ie 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

I think the correct way to specify a closure is like this:

func showAlertController( titleOfAlert: String, messageOfAlert : String, doAction : (() -> Void) ){

   // and then call it like that
   doAction()

}

The key thing here is that you cannot call this.doAction() because the parameter you pass into the function is not a property on your controller, right ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM