我很难理解我遇到的问题.
为简化起见,我将使用UIView方法.
基本上,如果我写的方法
为简化起见,我将使用UIView方法.
基本上,如果我写的方法
UIView.animateWithDuration(1,animations: {() in },completion:{(Bool) in println("test") })
它工作正常.
现在,如果我做同样的方法,但创建一个像这样的字符串:
UIView.animateWithDuration(1,completion:{(Bool) in String(23) })
现在,这是奇怪的部分.如果我执行与失败的代码完全相同的代码,但只需添加如下的打印命令:
UIView.animateWithDuration(1,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,posterPath: posterPath) self.delegate?.imageDownloader(self,posterPath: posterPath) }
解决方法
Swift中的闭包只有一个表达式时才有
implicit returns.这允许简洁的代码,例如:
reversed = sorted(names,{ s1,s2 in s1 > s2 } )
在您的情况下,当您在此处创建字符串时:
UIView.animateWithDuration(1,animations: {() in },completion:{(Bool) in String(23) })
你最终返回该字符串,这使得你的闭包签名:
(Bool) -> String
这不再匹配animateWithDuration的签名所需的内容(这会在调用错误中转换为Swift对参数’delay’的神秘缺失参数,因为它无法找到匹配的适当签名).
一个简单的解决方法是在闭包结束时添加一个空的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) }
因为那里有两个表达式,而不仅仅是一个表达式;隐式返回仅在闭包包含单个表达式时发生.因此,该闭包不会返回任何内容并且与其签名相匹配.
原文地址:https://www.jb51.cc/iOS/332608.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。