如何在Swift 3和4中编写dispatch_after GCD?
在Swift 2中,我能够使用 dispatch_after
来延迟使用大中央调度的行动:
In Swift 2, I was able to use dispatch_after
to delay an action using grand central dispatch:
var dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
// your function here
})
但这似乎不再在Swift 3(或4)中编译。在Swift 3中使用新的Dispatch API编写它的首选方法是什么?
But this no longer seems to compile in Swift 3 (or 4). What is the preferred way to write this in Swift 3 (using the new Dispatch API)?
语法很简单:
// to run something in 0.1 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
// your code here
}
注意,上面添加秒
作为 Double
的语法似乎是混乱的来源(特别是因为我们习惯于添加nsec)。 将秒加为 Double
语法有效,因为截止日期
是 DispatchTime
并且,在幕后,有一个 +
运算符,它将采用 Double
并添加那么多秒到 DispatchTime
:
Note, the above syntax of adding seconds
as a Double
seems to be a source of confusion (esp since we were accustomed to adding nsec). That "add seconds as Double
" syntax works because deadline
is a DispatchTime
and, behind the scenes, there is a +
operator that will take a Double
and add that many seconds to the DispatchTime
:
public func +(time: DispatchTime, seconds: Double) -> DispatchTime
但是,如果你真的想要将整数msec,μs或nsec添加到 DispatchTime
,您还可以将 DispatchTimeInterval
添加到 DispatchTime
。这意味着你可以这样做:
But, if you really want to add an integer number of msec, μs, or nsec to the DispatchTime
, you can also add a DispatchTimeInterval
to a DispatchTime
. That means you can do:
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) {
os_log("500 msec seconds later")
}
DispatchQueue.main.asyncAfter(deadline: .now() + .microseconds(1_000_000)) {
os_log("1m μs seconds later")
}
DispatchQueue.main.asyncAfter(deadline: .now() + .nanoseconds(1_500_000_000)) {
os_log("1.5b nsec seconds later")
}
由于这种单独的重载方法,所有这些都无缝地工作对于 DispatchTime
类中的 +
运算符。
These all seamlessly work because of this separate overload method for the +
operator in the DispatchTime
class.
public func +(time: DispatchTime, interval: DispatchTimeInterval) -> DispatchTime