Swift 使用闭包作为函数参数时,不带逗号的单独参数
Swift seperate parameter without a comma when using closures as a function parameter
在 Swift 1.1 和 Xcode 6.2 中,我想了解这里发生了什么:
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
}
}
理想情况下,我想阅读解释为什么允许此行为及其名称的文档的一部分。 (或者我错过了什么?)。
这是否只允许关闭? (我可以看到我可以省略很多带闭包的东西,比如括号和 return 语句)。
蒂亚
这称为 尾随闭包。来自官方文档:
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
在 Swift 1.1 和 Xcode 6.2 中,我想了解这里发生了什么:
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
}
}
理想情况下,我想阅读解释为什么允许此行为及其名称的文档的一部分。 (或者我错过了什么?)。
这是否只允许关闭? (我可以看到我可以省略很多带闭包的东西,比如括号和 return 语句)。
蒂亚
这称为 尾随闭包。来自官方文档:
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