2014-09-24 38 views
2

我是新來的swift,我需要幫助閱讀下面的代碼。如何在函數調用後讀取代碼塊?

  1. 什麼是代碼塊的函數調用「self.table.update(completedItem)」 {...}
  2. 後的含義是什麼(結果,錯誤)的含義爲代碼塊的第一行:

    self.table .update(completedItem){在 // (結果,錯誤)...來代碼 }

全碼:

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) 
    { 
     let record = self.records[indexPath.row] 
     let completedItem = record.mutableCopy() as NSMutableDictionary 
     completedItem["complete"] = true 

     UIApplication.sharedApplication().networkActivityIndicatorVisible = true 
     self.table!.update(completedItem) { 
      (result, error) in 

      UIApplication.sharedApplication().networkActivityIndicatorVisible = false 
      if error != nil { 
       println("Error: " + error.description) 
       return 
      } 

      self.records.removeAtIndex(indexPath.row) 
      self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) 
     } 
    } 

回答

3
  1. 的代碼塊被稱爲「後閉合」。當函數或方法將閉包作爲最後一個參數時,可以將閉包放在函數/方法調用的右括號之後。尾隨閉包允許您編寫看起來更像內置控制結構的函數,並且可以避免在括號內嵌套大括號。

例如,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:塊使用尾隨閉包。

  1. (result, error)部分聲明塊的參數的名稱。我推斷,update方法有一個簽名是這樣的:

    func update(completedItem: NSMutableDictionary, 
        completion: (NSData!, NSError!) -> Void) 
    

因此,它有兩個參數來調用完成塊。爲了訪問這些參數,該塊給它們起名爲resulterror。您不必指定參數類型,因爲編譯器可以根據update的聲明推斷出類型。

注意,你其實可以省略參數名稱和使用簡寫名稱$0$1:通過閱讀「Closures」 in The Swift Programming Language

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) 
} 

您可以瞭解更多關於關閉。

相關問題