【问题标题】:Nested Closures in Swift 2.1Swift 2.1 中的嵌套闭包
【发布时间】:2015-11-08 07:39:18
【问题描述】:

我想澄清一下 Swift 2.1 中的嵌套闭包

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

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

然后我使用这个nestedDownload闭包作为下面函数的参数,并尝试在as这样的函数中完成编译参数值

func nestedDownloadCheck(compliletion:nestedDownload){

        compliletion(FirstItem: "firstItem")
}

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

另外,当我从ViewDidLoad() 方法调用nestedDownloadCheck() 时,通过tring 填充编译的主体

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


            }
            return OptionalFunction("response")
        }

这表示编译错误“Cannot convert return expression of type 'Void'(aka'()') to return Type '(SecondString: String!) -> Void'

我不知道我究竟是如何以这种方式使用嵌套闭包的。

【问题讨论】:

    标签: ios swift2 ios9 ios9.1 swift2.1


    【解决方案1】:

    您必须返回实际的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")
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多