ios – Swift完成块

ios – Swift完成块,第1张

概述我很难理解我遇到的问题. 为简化起见,我将使用UIView方法. 基本上,如果我写的方法 UIView.animateWithDuration(1, animations: {() in }, completion:{(Bool) in println("test") }) 它工作正常. 现在,如果我做同样的方法,但创建一个像这样的字符串: UI 我很难理解我遇到的问题.
为简化起见,我将使用UIVIEw方法.
基本上,如果我写的方法
UIVIEw.animateWithDuration(1,animations:  {() in        },completion:{(Bool)  in            println("test")    })

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

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

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

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

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)}

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

总结

以上是内存溢出为你收集整理的ios – Swift完成块全部内容,希望文章能够帮你解决ios – Swift完成块所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1101778.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-28
下一篇2022-05-28

发表评论

登录后才能评论

评论列表(0条)

    保存