2014-09-21 72 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