[英]Super simple trailing closure syntax in Swift
这是功能:
func someFunctionThatTakesAClosure(closure: () -> Void) {
// function body goes here
print("we do something here and then go back")//does not print
}
我在这里称呼它。
print("about to call function")//prints ok
someFunctionThatTakesAClosure(closure: {
print("we did what was in the function and can now do something else")//does not print
})
print("after calling function")//prints ok
但是,该函数没有被调用。 上面有什么问题?
这是Apple的示例:
func someFunctionThatTakesAClosure(closure:()-> Void){//函数体在这里}
//以下是不使用尾随闭包而调用此函数的方式:
someFunctionThatTakesAClosure(closure:{//封闭体在这里})
文档对您所需的解释不是很清楚
print("1")
someFunctionThatTakesAClosure() { // can be also someFunctionThatTakesAClosure { without ()
print("3")
}
func someFunctionThatTakesAClosure(closure: () -> Void) {
print("2")
/// do you job here and line blow will get you back
closure()
}
尾随闭包用于完成操作,例如当您执行网络请求并最终返回响应时
func someFunctionThatTakesAClosure(completion: @escaping ([String]) -> Void) {
print("inside the function body")
Api.getData {
completion(arr)
}
}
并致电
print("Before calling the function")
someFunctionThatTakesAClosure { (arr) in
print("Inside the function callback / trailing closure " , arr)
}
print("After calling the function")
你错过了读什么
这是固定的示例:
func someFunctionThatTakesAClosure(closure: () -> Void) {
// function body goes here
print("we do something here and then go back")
// don't forget to call the closure
closure()
}
print("about to call function")
// call the function using trailing closure syntax
someFunctionThatTakesAClosure() {
print("we did what was in the function and can now do something else")
}
print("after calling function")
输出:
about to call function we do something here and then go back we did what was in the function and can now do something else after calling function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.