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

54,676

Solution 1

  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, 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).

Solution 2

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

Share:
54,676
SergeH
Author by

SergeH

Updated on October 11, 2020

Comments

  • SergeH
    SergeH over 3 years

    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 ?