我想清除Swift 2.1中的嵌套闭包

我在这里声明一个嵌套的闭包,

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

然后,我将此nestedDownload闭包用作以下函数的参数,并尝试完成如下函数中的完成参数值:
func nestedDownloadCheck(compliletion:nestedDownload){

        compliletion(FirstItem: "firstItem")
}

但这表示错误“表达式解析为未使用的函数

此外,当我通过tring填充编译主体从nestedDownloadCheck()方法调用ViewDidLoad()
self.nestedDownloadCheck { (FirstString) -> (SecondString: String!) -> Void in
            func OptionalFunction(var string:String)->Void{


            }
            return OptionalFunction("response")
        }

这表示编译错误“无法将类型'Void'(aka'()')的返回表达式转换为类型'(SecondString:String!)-> Void'

我不知道如何以这种方式完全使用嵌套的闭包。

最佳答案

您必须返回实际的OptionalFunction,而不用"response"调用它并返回该值。 ,您必须在定义中使用String!:

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

    }
    return OptionalFunction
}

请注意,函数应以小写字母开头:optionalFunction

您的代码的作用是
  • 定义一个称为OptionalFunction的函数
  • "response"作为参数
  • 调用该函数
  • 返回该调用返回的值(Void)

  • 因此,编译器正确地告诉您Void无法转换为(SecondString: String!) -> Void的预期返回值

    您最后缺少的是像这样调用实际返回的函数:
    func nestedDownloadCheck(compliletion:nestedDownload){
        compliletion(FirstItem: "firstItem")(SencondItem: "secondItem")
    }
    

    关于ios - Swift 2.1中的嵌套闭包,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33591777/

    10-12 03:35