How to read code block after a function call?

前端 未结 1 1971
不思量自难忘°
不思量自难忘° 2021-01-22 10:33

I am new to swift, I need help in reading the following code.

  1. what is the meaning of the code block after the function call \"self.table.update(completedItem)\" {.
1条回答
  •  梦毁少年i
    2021-01-22 11:10

    1. The code block is called a “trailing closure”. When a function or method takes a closure as the last argument, you can put the closure after the closing parenthesis of the function/method call. The trailing closure lets you write functions that look more like built-in control structures, and lets you avoid nesting braces inside parentheses.

    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.

    1. 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.

    0 讨论(0)
提交回复
热议问题