2014-09-21 70 views
7

我很難理解我遇到的問題。 爲了簡化,我將使用UIView方法。 基本上,如果我寫的方法Swift完成塊

UIView.animateWithDuration(1, animations: {() in 
     }, completion:{(Bool) in 
      println("test") 
    }) 

它工作正常。 現在,如果我做同樣的方法,但創建一個字符串,像這樣:

UIView.animateWithDuration(1, animations: {() in 
     }, completion:{(Bool) in 
      String(23) 
    }) 

它停止工作。編譯器錯誤:通話中參數'延遲'缺少參數

現在,這裏是奇怪的部分。如果我做同樣的代碼失敗的一個,但只需添加一個打印命令,像這樣:

UIView.animateWithDuration(1, animations: {() in 
     }, completion:{(Bool) in 
      String(23) 
      println("test") 
    }) 

它開始重新工作。

我的問題基本上是一樣的。我的代碼:

downloadImage(filePath, url: url) {() -> Void in 
     self.delegate?.imageDownloader(self, posterPath: posterPath) 
     } 

不起作用。但如果我改變。

downloadImage(filePath, url: url) {() -> Void in 
      self.delegate?.imageDownloader(self, posterPath: posterPath) 
       println("test") 
      } 

甚至:

downloadImage(filePath, url: url) {() -> Void in 
      self.delegate?.imageDownloader(self, posterPath: posterPath) 
      self.delegate?.imageDownloader(self, posterPath: posterPath) 
      } 

它工作正常。 我不明白爲什麼會發生這種情況。我接近接受這是一個編譯器錯誤。

回答

10

閉包在夫特具有implicit returns當它們僅由一個單一表達的。這允許簡潔的代碼,例如這樣的:

reversed = sorted(names, { s1, s2 in s1 > s2 }) 

在你的情況,當你創建的字符串在這裏:

UIView.animateWithDuration(1, animations: {() in }, completion:{(Bool) in 
    String(23) 
}) 

你最終返回該字符串,使您關閉的簽名:

(Bool) -> String 

不再匹配什麼是由animateWithDuration的簽名(這相當於斯威夫特的神祕Missing argument for parameter 'delay' in call錯誤,因爲它不能要求科幻找到適當的簽名進行匹配)。

一個簡單的辦法就是在你關閉的末尾添加一個空的return語句:

UIView.animateWithDuration(1, animations: {() in}, completion:{(Bool) in 
    String(23) 
    return 
}) 

,讓您的簽名應該是什麼:

(Bool) ->() 

你的最後一個例子:

downloadImage(filePath, url: url) {() -> Void in 
    self.delegate?.imageDownloader(self, posterPath: posterPath) 
    self.delegate?.imageDownloader(self, posterPath: posterPath) 
} 

工作,因爲有兩個表達式,不只是一個;隱式返回僅在閉包含單個表達式時發生。所以,封閉不會返回任何符合其簽名的內容。

+0

謝謝。但是,爲什麼它不會失敗,如果我添加字符串(23)並再次複製相同的行,如:String(23);串(23); ? – Wak 2014-09-21 02:45:57

+0

我實際上是在澄清,在答案中。請參閱編輯。 – 2014-09-21 02:50:13

+0

感謝您的回答;幫助我弄清楚爲什麼我得到一個奇怪的「無法使用參數列表類型...」錯誤調用'animateWithDuration'。原來的解決方案是完全一樣的。 – SonarJetLens 2014-10-06 12:39:49