ios - 使用闭包作为函数参数时,Swift 不带逗号的单独参数

标签 ios swift xcode6

在带有 Xcode 6.2 的 Swift 1.1 中,我想了解这里发生了什么:

ExampleInfo(title: item.title) { self.getItemById(item.uniqueId) }

为什么这和:

ExampleInfo(title: item.title, { self.getItemById(item.uniqueId) })

这就是我正在构建的:

class ExampleInfo : NSObject {

    let title : NSString
    var exampleFunc: () -> (UIViewController)

    init(title: NSString, example exampleFunc:() -> (UIViewController)) {
        self.exampleFunc = exampleFunc
        self.title = title
    }
}

理想情况下,我想阅读解释为什么允许这种行为及其名称的文档的一部分。 (或者我错过了什么?)。

这是否只允许关闭? (我可以看到我可以省略很多带闭包的东西,比如括号和返回语句)。

蒂亚

最佳答案

这称为尾随闭包。来自官方文档:

If you need to pass a closure expression to a function as the function’s final argument and the closure expression is long, it can be useful to write it as a trailing closure instead. A trailing closure is a closure expression that is written outside of (and after) the parentheses of the function call it supports.

在此处的官方文档中阅读更多内容 - https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html

关于ios - 使用闭包作为函数参数时,Swift 不带逗号的单独参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29536735/

相关文章:

swift - 以一定的速度在屏幕上移动一个对象。(Sprite Kit)

objective-c - 如何更改 Swift 类的命名空间?

ios - XCode6 storyboard,TableViewController看不到navigation Items

ios - 运行时遇到错误(域 = LaunchServicesError,代码 = 0)

ios - 显示键盘时禁用按钮

ios - 我是否必须在 Metal 中指定深度纹理,还是自动为我分配一个深度纹理?

iphone - ifdef语法不起作用

ios - 在 iTunes Connect 中创建用户时出错 : Invalid Year

ios - 仅在设备(iphone 和 ipad)上发生错误 - 链接器命令失败

swift 。 unowned 相对于 weak 性能的(绝对)唯一特定优势是什么?