Swift Closure中的返回types必须是Void的可选链接

我正在创build一个应该有自己的run()实现的脚本的双向链接列表( MSScript run() ,并且在他们准备好时调用下一个脚本( rscript )。 我想创build的一个脚本只是一个延迟。 它看起来像这样:

 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的最后一行,它不会编译,这是因为从可选链接run()更改返回types 。 我随机决定插入Void.self ,它解决了这个问题,但我不知道为什么。

什么是这个Void.self ,这是正确的解决scheme?

可选的链接包装任何右侧的结果是可选的。 所以如果run()返回T ,那么x?.run()返回T? 。 由于run()返回Void (aka () ),这意味着整个可选链expression式的types为Void? (或()? )。

当闭包只有一行时,隐含地返回该行的内容。 所以,如果你只有这一行,就好像你写了return weakSelf.rscript?.run() 。 所以你正在返回typesVoid? ,但是dispatch_async需要一个返回Void的函数。 所以他们不匹配。

一种解决方法是添加另一行,显式返回任何内容:

 dispatch_after(time, dispatch_get_main_queue()) { weakSelf.rscript?.run() return }