ios – Swift完成块

前端之家收集整理的这篇文章主要介绍了ios – Swift完成块前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我很难理解我遇到的问题.
为简化起见,我将使用UIView方法.
基本上,如果我写的方法
  1. UIView.animateWithDuration(1,animations: {() in
  2. },completion:{(Bool) in
  3. println("test")
  4. })

它工作正常.
现在,如果我做同样的方法,但创建一个像这样的字符串:

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

它停止工作.编译器错误调用中缺少参数’delay’的参数

现在,这是奇怪的部分.如果我执行与失败的代码完全相同的代码,但只需添加如下的打印命令:

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

它又开始起作用了.

我的问题基本上是一回事.我的代码

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

不起作用.但如果我换到.

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

甚至:

  1. downloadImage(filePath,posterPath: posterPath)
  2. self.delegate?.imageDownloader(self,posterPath: posterPath)
  3. }

它工作正常.
我不明白为什么会这样.我接近它接受它是一个编译器错误.

解决方法

Swift中的闭包只有一个表达式时才有 implicit returns.这允许简洁的代码,例如:
  1. reversed = sorted(names,{ s1,s2 in s1 > s2 } )

在您的情况下,当您在此处创建字符串时:

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

你最终返回该字符串,这使得你的闭包签名:

  1. (Bool) -> String

这不再匹配animateWithDuration的签名所需的内容(这会在调用错误中转换为Swift对参数’delay’的神秘缺失参数,因为它无法找到匹配的适当签名).

一个简单的解决方法是在闭包结束时添加一个空的return语句:

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

这使你的签名应该是什么:

  1. (Bool) -> ()

你最后一个例子:

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

因为那里有两个表达式,而不仅仅是一个表达式;隐式返回仅在闭包包含单个表达式时发生.因此,该闭包不会返回任何内容并且与其签名相匹配.

猜你在找的iOS相关文章