2014-09-24 37 views
11

一個UIView需要根據自定義的控制完成處理程序,以改變警告標籤:嵌套關閉不喜歡的參數列表

voucherInputView.completionHandler = {[weak self] (success: Bool) -> Void in 

     self?.proceedButton.enabled = success 
     self?.warningLabel.alpha = 1.0 

     if success 
     { 
      self?.warningLabel.text = "Code you entered is correct" 
      self?.warningLabel.backgroundColor = UIColor.greenColor() 
     } 
     else 
     { 
      self?.warningLabel.text = "Code you entered is incorrect" 
      self?.warningLabel.backgroundColor = UIColor.orangeColor() 
     } 


     UIView.animateWithDuration(NSTimeInterval(1.0), animations:{()-> Void in 
      self?.warningLabel.alpha = 1.0 
     }) 

最終的動畫塊顯示形式的錯誤。

Cannot invoke 'animateWithDuration' with an argument list of type '(NSTimeInterval), animations:()-> Void)' 

如果我稱之爲完成關閉之外的某個地方,它可以工作。

回答

39

的問題是,封閉被隱式返回該表達式的結果:

self?.warningLabel.alpha = 1.0 

但蓋子本身被聲明爲返回Void

添加一個明確的return應該解決的問題:

UIView.animateWithDuration(NSTimeInterval(1.0), animations: {()-> Void in 
    self?.warningLabel.alpha = 1.0 
    return 
}) 
+0

非常感謝=)!! – 2014-09-24 17:06:07

+5

這對我來說是固定的,但是有人會介意解釋*爲什麼這種行爲對於很多人來說是如此奇怪和令人意想不到的?順便說一句,在你的例子中,你可以用'_'替換'() - > Void',並用';'追加返回。返回'到同一行。另外,你可以寫'; ()'而不是單行'return'。 :) – BastiBen 2014-12-17 10:41:58

+0

這是正確的答案! – 2015-01-25 16:08:32

0

安東尼奧的解決方案也適用於嵌套的閉包,喜歡做UITableViewRowAction處理程序內的AFNetworking請求。

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? { 

    let cleanRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Do Stuff", handler: {[weak self](action: UITableViewRowAction!, indexPath: NSIndexPath!) in 

     AFHTTPSessionManager(baseURL: NSURL(string: "http://baseurl")).PUT("/api/", parameters: nil, success: { (task: NSURLSessionDataTask!, response: AnyObject!) -> Void in 

       // Handle success 

       self?.endEditing() 
       return 
      }, failure: { (task: NSURLSessionDataTask!, error: NSError!) -> Void in 

       // Handle error 

       self?.endEditing() 
       return 
     }) 
     return 

    }) 

    cleanRowAction.backgroundColor = UIColor.greenColor() 
    return [cleanRowAction] 
}