Swift 2.1中的嵌套闭包 [英] Nested Closures in Swift 2.1
问题描述
我想清楚Swift 2.1中的嵌套闭包
这里我声明了一个嵌套闭包,
Here I declare a nested closure,
typealias nestedDownload = (FirstItem: String!)-> (SencondItem: String!)->Void
然后我用这个 nestedDownload
闭包作为以下函数的参数,并尝试在函数中完成compliletion参数值,如:
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")
}
但这表示错误,表达式解析为未使用的函数
此外,当我打电话时 nestedDownloadCheck()
来自 ViewDidLoad()
方法来填充汇编的正文
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")
}
这表示编译错误无法转换'Void'类型的返回表达式(又名'() ')返回Type'(SecondString:String!) - > Void'
我无法弄清楚我是如何使用嵌套闭包的这样。
I can't find out how I exactly use the nested closure in this way .
推荐答案
你必须返回实际的 OptionalFunction
,而不是使用response
调用它并返回该值。 你必须在定义中使用 String!
:
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
}
请注意,函数应以小写字母开头: optionalFunction
。
Note that functions should start with a lower case letter: optionalFunction
.
您的代码所做的是
- 定义一个名为
OptionalFunction的函数
- 调用函数与
response
作为参数 - 返回该调用返回的值(
Void
)
- define a function called
OptionalFunction
- call that function with
"response"
as parameter - return the value returned by that invocation (
Void
)
编译器因此正确地告诉你
Void
无法转换为的预期回报值(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")
}
这篇关于Swift 2.1中的嵌套闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!