- 该代码块称为“尾随闭包”。当函数或方法采用闭包作为最后一个参数时,可以将闭包放在函数/方法调用的右括号后面。尾随闭包可让您编写看起来更像内置控制结构的函数,并可让您避免在圆括号内嵌套大括号。
例如,UIView
定义具有以下签名的类方法:
class func animateWithDuration(duration: NSTimeInterval, animations: () -> Void)
所以你可以这样称呼它:
UIView.animateWithDuration(0.2, animations: {
self.view.alpha = 0
})
或者您可以使用尾随闭包来调用它,如下所示:
UIView.animateWithDuration(0.2) {
self.view.alpha = 0
}
请注意,使用尾随闭包时,您完全省略了关键字 (animations:
)最后一个参数。
您只能对函数的最后一个参数使用尾随闭包。例如,如果您使用UIView.animateWithDuration(animations:completion:)
,你必须把animations:
括号内的块,但您可以使用尾随闭包completion:
block.
-
The (result, error)
部分声明块参数的名称。我推断update
方法有一个类似这样的签名:
func update(completedItem: NSMutableDictionary,
completion: (NSData!, NSError!) -> Void)
因此它用两个参数调用完成块。为了访问这些参数,该块为它们提供了名称result
and error
。您不必指定参数类型,因为编译器可以根据update
的声明。
请注意,实际上您可以省略参数名称并使用简写名称$0
and $1
:
self.table!.update(completedItem) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if $1 != nil {
println("Error: " + $1.description)
return
}
self.records.removeAtIndex(indexPath.row)
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
您可以通过阅读了解有关闭包的更多信息中的“关闭”Swift 编程语言.