【问题标题】:Super simple trailing closure syntax in SwiftSwift 中超级简单的尾随闭包语法
【发布时间】:2019-08-14 00:11:57
【问题描述】:

我正在尝试关注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(闭包:{ // 闭包的主体放在这里 })

【问题讨论】:

  • 闭包只是一个值。就像任何其他值一样,您可以“忽略”它的存在并且什么都不会发生。让任何事情发生都需要您实际使用该值。

标签: ios swift closures trailing


【解决方案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") 

你错过了什么

【讨论】:

  • 谢谢,我看到了,但读起来好像你可以使用任何一个。谢谢澄清!我赞成答案。
【解决方案2】:

这是你的例子:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 2020-10-09
    • 2018-03-27
    • 1970-01-01
    • 2016-09-26
    • 2018-05-02
    • 1970-01-01
    相关资源
    最近更新 更多