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

问题描述 投票:0回答:2

我试图跟随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

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

这是Apple的例子:

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

//这是你在不使用尾随闭包的情况下调用这个函数的方法:

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

ios swift closures trailing
2个回答
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

1
投票

Docs对你需要的解释不是很清楚

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

© www.soinside.com 2019 - 2024. All rights reserved.