ios – Swift Closure中的可选链接,返回类型必须为Void
2019年06月24日
作者:佚名
我正在创建一个双重链接的脚本列表(MSScripts),它们应该有自己的run()实现,并且在它们准备就绪时调用下一个脚本(rscript).我想创建的一个脚本只是一个延迟.它看起来像这样:
class DelayScript : MSScript { var delay = 0.0 override func run() { let delay = self.delay * Double(NSEC_PER_SEC) let time = dispatch_time(DISPATCH_TIME_NOW,Int64(delay)) let weakSelf = self dispatch_after(time,dispatch_get_main_queue()) { weakSelf.rscript?.run() Void.self } } init(delay: Double) { super.init() self.delay = delay } }
其中rscript是下一个要运行的脚本.问题是,如果我删除dispatch_after的最后一行,它不会编译,那是因为the changed return type of run() from optional chaining.我随机决定插入Void.self并修复了问题,但我不明白为什么.
什么是Void.self,它是正确的解决方案吗?
解决方法
可选的链接包装右侧的结果是可选的.因此,如果run()返回T,则x?.run()返回T?.由于run()返回Void(a.k.a.()),这意味着整个可选链接表达式的类型为Void? (要么 ()?).
当闭包只有一行时,隐式返回该行的内容.所以,如果你只有那一行,就好像你写了返回weakSelf.rscript?.run().所以你要返回类型Void?,但是dispatch_async需要一个返回Void的函数.所以他们不匹配.
一种解决方案是添加另一行显式不返回任何内容:
dispatch_after(time,dispatch_get_main_queue()) { weakSelf.rscript?.run() return }
以上是来客网为你收集整理的ios – Swift Closure中的可选链接,返回类型必须为Void全部内容,希望文章能够帮你解决ios – Swift Closure中的可选链接,返回类型必须为Void所遇到的程序开发问题。
如果觉得来客网网站内容还不错,欢迎将来客网网站推荐给程序员好友。