I am new to swift, I need help in reading the following code.
For example, UIView
defines a class method with this signature:
class func animateWithDuration(duration: NSTimeInterval, animations: () -> Void)
So you can call it like this:
UIView.animateWithDuration(0.2, animations: {
self.view.alpha = 0
})
or you can call it with a trailing closure, like this:
UIView.animateWithDuration(0.2) {
self.view.alpha = 0
}
Note that with a trailing closure, you entirely omit the keyword (animations:
) of the last argument.
You can only use a trailing closure for the very last argument of the function. For example, if you use UIView.animateWithDuration(animations:completion:)
, you must put the animations:
block inside the parentheses, but you can use a trailing closure for the completion:
block.
The (result, error)
part declares names for the arguments to the block. I deduce that the update
method has a signature something like this:
func update(completedItem: NSMutableDictionary,
completion: (NSData!, NSError!) -> Void)
So it calls the completion block with two arguments. To access those arguments, the block gives them the names result
and error
. You don't have to specify the argument types because the compiler can deduce the types based on update
's declaration.
Note that you can in fact omit the argument names and use the shorthand names $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)
}
You can learn more about closures by reading “Closures” in The Swift Programming Language.