Swift中的超级简单的尾随闭包语法

时间:2019-03-22 23:58:07

标签: ios swift closures trailing

我正在尝试遵循example in the Swift docs进行结尾关闭。

这是功能:

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

但是,未调用该函数。上面有什么问题?

这是苹果公司的例子:

  

func someFunctionThatTakesAClosure(closure:()-> Void){       //函数体在这里}

     

//以下是在不使用结尾闭包的情况下调用此函数的方式:

     

someFunctionThatTakesAClosure(关闭:{       //闭包的主体在这里})

2 个答案:

答案 0 :(得分:1)

您对文档的解释不够清楚

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") 

您错过阅读的内容

enter image description here

答案 1 :(得分:1)

以下是您的固定示例:

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