Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 288
SergeH Avatar asked Dec 26 '15 11:12

SergeH


2 Answers

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

like image 129
luk2302 Avatar answered Nov 17 '22 09:11

luk2302


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

like image 33
Nikita Kurtin Avatar answered Nov 17 '22 09:11

Nikita Kurtin