Search code examples
iosios9ios9.1swift2

Nested Closures in Swift 2.1


I want to clear about Nested Closures in Swift 2.1

Here I declare a nested closure,

  typealias nestedDownload = (FirstItem: String!)-> (SencondItem: String!)->Void

Then I use this nestedDownload closure as a parameter of the following function and try to complete the compliletion parameter value in function like as

func nestedDownloadCheck(compliletion:nestedDownload){

        compliletion(FirstItem: "firstItem")
}

But this says the error, "Expression resolves to an unused function"

Also , when I call nestedDownloadCheck() from ViewDidLoad() method by tring to fill the body of the compilation

self.nestedDownloadCheck { (FirstString) -> (SecondString: String!) -> Void in
            func OptionalFunction(var string:String)->Void{


            }
            return OptionalFunction("response")
        }

This says the compilation error "Cannot convert return expression of type 'Void'(aka'()') to return Type '(SecondString: String!) -> Void' "

I can't find out how I exactly use the nested closure in this way .


Solution

  • You have to return the actual OptionalFunction, not invoke it with "response" and return that value. And you have to use String! in the definition:

    nestedDownloadCheck { (FirstString) -> (SecondString: String!) -> Void in
        func OptionalFunction(inputString:String!) -> Void {
    
        }
        return OptionalFunction
    }
    

    Note that functions should start with a lower case letter: optionalFunction.

    What your code does is

    • define a function called OptionalFunction
    • call that function with "response" as parameter
    • return the value returned by that invocation (Void)

    The compiler therefore correctly tells you that Void is no convertible to the expected return value of (SecondString: String!) -> Void

    What you are finally missing is to invoke the actual returned function like so:

    func nestedDownloadCheck(compliletion:nestedDownload){
        compliletion(FirstItem: "firstItem")(SencondItem: "secondItem")
    }