首页 > 解决方案 > 为什么闭包的实际主体永远不会被执行?

问题描述

来自 Apple 的 Swift 编程语言(Swift 5.2 Beta)

func someFunctionThatTakesAClosure(closure: () -> Void) {
    // function body goes here
       print("Declaring Function")
}

// Here's how you call this function without using a trailing closure:

someFunctionThatTakesAClosure(closure: {
    // closure's body goes here
       print("Without Trailing Closure Syntax")
})

// Here's how you call this function with a trailing closure instead:

someFunctionThatTakesAClosure() {
    // trailing closure's body goes here
       print("Trailing Closure Syntax")
}

摘自:Apple Inc. “The Swift Programming Language (Swift 5.2 beta)”。苹果图书。

在这些示例中,它在someFunctionThatTakesAClosure被调用两次时只打印两次声明函数,我想知道这两个闭包的主体是如何没有被调用的?

标签: iosswift

解决方案


您需要更改为以下内容:

func someFunctionThatTakesAClosure(closure: () -> Void) {
   print("Declaring Function")
   closure()
}

推荐阅读