简体   繁体   中英

Using predefined function with parameters as completion block in swift

EDIT: I thought the issue was Swift syntax, but the problem was that I did not know that the UIViewController.presentViewController specifies a signature for the completion handler that takes no input parameters.

I have to provide a completion handler to presentViewController. The completion handler I want to provide takes an input parameter. What is the syntax to handle this in swift?

If the handler did not take an input parameter it would look like this:

self.presentViewController(activityVC, animated: true, completion: myHandler)

But how would the above line look if myHandler was declared like this:

func myHandler(myParameter: AnyObject){
    ...
}

I should have looked at the declaration of presentViewController before asking the question, but I am inexperienced with closures and thought any closure could be passed. It turns out that the issue is that presentViewController takes a very specific closure of the form

(() -> Void)?

The full signature is here:

func presentViewController(_ viewControllerToPresent: UIViewController,
              animated flag: Bool,
            completion completion: (() -> Void)?)

So the answer is that presentViewController cannot take a completion handler that itself takes another parameter.

I believe you are looking to do the following:

function myHandler(myParameter: (() -> Void)) {
//code here
}

Of course -> Void would change depending on if you want the function

That does not work unfortunately. You cannot just pass in a function that has an invalid type for the completion block. It expects a closure without any parameters and with no return type / void . You are providing a function that expects a AnyObject and returns nothing / void . Therefore there is a mismatch between the expected (() -> Void) and the provided ((AnyObject) -> Void)

How would the program know what to pass in to myHandler as myParameter ?

The only way I can think of to achieve this is to write a wrapper for the custom completion handler:

self.presentViewController(activityVC, animated: true, completion:{self.myHandler("")})

That way you provide a completion block that calls the myHandler but actually provides a value for myParameter .

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