Swift Closure的可选链接,其返回类型必须为Void
问题说明
我创建一个脚本( MSScript
s)的双向链表,它们应该有自己的 run()
实现,当他们准备好时,他们调用下一个脚本( rscript
)。我想创建的一个脚本只是一个延迟。它看起来像这样:
I am creating a doubly-linked-list of scripts (MSScript
s) 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?
正确答案
可选链接包装,不管右侧的结果是否在可选。因此,如果 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
-
复制文件夹/文件而不修改属性?
it1352 07-15 -
Reaction本机IOS Safari没办法打开页面,因为该地址在有效登录后无效
it1352 06-07 -
使用c++17更新时出现G++编译器警告
it1352 06-18 -
应用已在 Play 商店发布,但未显示在平板电脑上
it1352 07-20 -
在没有特定应用程序的情况下读取 NFC 标签?
it1352 08-02 -
在不打开短信界面的情况下从 iPhone 应用发送短信?
it1352 07-25 -
从iOS应用程序打开Telegram聊天(使用Bot)
it1352 06-07 -
手机号码拆分为国家代码、地区代码和本地号码?
it1352 09-15 -
条形码(代码128)字体不能扫描有问题
it1352 06-09 -
检测是否安装了 Microsoft Edge?
it1352 08-02