• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Swift Closure的可选链接,其返回类型必须为Void

用户头像
it1352
帮助1

问题说明

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

I am creating a doubly-linked-list of scripts (MSScripts) that are supposed to have their own run() implementation, and they call the next script (rscript) when they're ready . One of the scripts I'd like to create is just a delay. It looks like this:

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()的返回类型。我随机决定插入 Void.self ,它解决了问题,但我不知道为什么。

Where rscript is the next script to run. The problem is that if I remove the last line of the dispatch_after, it doesn't compile, and that's because of the changed return type of run() from optional chaining. I randomly decided to insert Void.self and it fixed the problem, but I have no idea why.

是这个 Void.self ,是否是正确的解决方案?

What is this Void.self, and is it the right solution?

正确答案

#1

可选链接包装,不管右侧的结果是否在可选。因此,如果 run()返回 T ,则 x?.run()返回 T?。由于 run()返回 Void (aka ()) ,那意味着整个可选链接表达式具有类型 Void?(或()?)。

Optional chaining wraps whatever the result of the right side is inside an optional. So if run() returned T, then x?.run() returns T?. Since run() returns Void (a.k.a. ()), that means the whole optional chaining expression has type Void? (or ()?).

当闭包只有一行时,隐式返回该行的内容。所以如果你只有那一行,就好像你写 return weakSelf.rscript?.run()。所以你返回类型 Void?,但是 dispatch_async 需要一个函数返回 Void 。因此它们不匹配。

When a closure has only one line, the contents of that line is implicitly returned. So if you only have that one line, it is as if you wrote return weakSelf.rscript?.run(). So you are returning type Void?, but dispatch_async needs a function that returns Void. So they don't match.

一个解决方案是添加另一行显式不返回任何内容:

One solution is to add another line that explicitly returns nothing:

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

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhbaeahi
系列文章
更多 icon
同类精品
更多 icon
继续加载